import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import ImageUser from "@/components/imageNew";
import Text from "@/components/Text";
import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiCreateDivision } from "@/lib/api";
import { setFormCreateDivision } from "@/lib/divisionCreate";
import { setUpdateDivision } from "@/lib/divisionUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { AntDesign } from "@expo/vector-icons";
import { router, Stack, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { Pressable, SafeAreaView, ScrollView, View } from "react-native";
import Toast from "react-native-toast-message";
import { useDispatch, useSelector } from "react-redux";

type Props = {
   idUser: string,
   name: string,
   img: string
}

export default function CreateDivisionAddAdmin() {
   const { token, decryptToken } = useAuthSession()
   const { id } = useLocalSearchParams<{ id: string }>()
   const [dataOld, setDataOld] = useState<Props[]>([])
   const [data, setData] = useState<Props[]>([])
   const [selectMember, setSelectMember] = useState<string[]>([])
   const update = useSelector((state: any) => state.divisionCreate)
   const updateDivision = useSelector((state: any) => state.divisionUpdate)
   const dispatch = useDispatch()
   const [loading, setLoading] = useState(false)

   async function handleLoadMember() {
      setData(update.member)
   }

   useEffect(() => {
      handleLoadMember()
   }, [])

   function onChoose(val: string) {
      if (selectMember.some((i: any) => i == val)) {
         setSelectMember(selectMember.filter((i: any) => i != val))
      } else {
         setSelectMember([...selectMember, val])
      }
   }

   async function handleAddMember() {
      try {
         setLoading(true)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiCreateDivision({ ...update, admin: selectMember, user: hasil })
         if (response.success) {
            Toast.show({ type: 'small', text1: 'Berhasil membuat divisi', })
            dispatch(setFormCreateDivision({ admin: [], member: [], data: { idGroup: '', name: '', desc: '' } }))
            dispatch(setUpdateDivision(!updateDivision))
            router.replace(`/division/`)
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error) {
         console.error(error)
         Toast.show({ type: 'small', text1: 'Terjadi kesalahan', })
      } finally {
         setLoading(false)
      }
   }


   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Pilih Admin Divisi',
               headerTitleAlign: 'center',
               headerRight: () => (
                  <ButtonSaveHeader
                     category="create"
                     disable={selectMember.length == 0 || loading ? true : false}
                     onPress={() => {
                        handleAddMember()
                     }}
                  />
               )
            }}
         />
         <View style={[Styles.p15]}>
            <ScrollView>
               {
                  data.length > 0 ?
                     data.map((item: any, index: any) => {
                        const found = dataOld.some((i: any) => i.idUser == item.id)
                        return (
                           <Pressable
                              key={index}
                              style={[Styles.itemSelectModal]}
                              onPress={() => {
                                 !found && onChoose(item.idUser)
                              }}
                           >
                              <View style={[Styles.rowItemsCenter, Styles.w70]}>
                                 <ImageUser src={`${ConstEnv.url_storage}/files/${item.img}`} border />
                                 <View style={[Styles.ml10]}>
                                    <Text style={[Styles.textDefault]} numberOfLines={1} ellipsizeMode="tail">{item.name}</Text>
                                    {
                                       found && <Text style={[Styles.textInformation, Styles.cGray]}>sudah menjadi anggota</Text>
                                    }
                                 </View>
                              </View>
                              {
                                 selectMember.some((i: any) => i == item.idUser) && <AntDesign name="check" size={20} color={'black'} />
                              }
                           </Pressable>
                        )
                     }
                     )
                     :
                     <Text style={[Styles.textDefault, { textAlign: 'center' }]}>Tidak ada data</Text>
               }
            </ScrollView>
         </View>
      </SafeAreaView>
   )
}