import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import ImageUser from "@/components/imageNew";
import ImageWithLabel from "@/components/imageWithLabel";
import InputSearch from "@/components/inputSearch";
import Text from "@/components/Text";
import Styles from "@/constants/Styles";
import { apiGetDivisionMember } from "@/lib/api";
import { setMemberChoose } from "@/lib/memberChoose";
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 AddMemberCreateTask() {
   const dispatch = useDispatch()
   const { token, decryptToken } = useAuthSession()
   const { id } = useLocalSearchParams<{ id: string, detail: string }>()
   const [data, setData] = useState<Props[]>([])
   const [selectMember, setSelectMember] = useState<any[]>([])
   const [search, setSearch] = useState('')
   const entitiesMember = useSelector((state: any) => state.memberChoose)

   async function handleLoadMemberDivision() {
      const hasil = await decryptToken(String(token?.current))
      const responMemberDivision = await apiGetDivisionMember({ id: id, user: hasil, search: search })
      setData(responMemberDivision.data)
      if (entitiesMember.length > 0) {
         setSelectMember(entitiesMember)
      }
   }

   useEffect(() => {
      handleLoadMemberDivision()
   }, [search]);

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

   async function handleAddMember() {
      try {
         dispatch(setMemberChoose(selectMember))
         router.back()
      } catch (error) {
         console.error(error)
         Toast.show({ type: 'small', text1: 'Gagal menambahkan anggota', })
      }
   }


   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Pilih Anggota',
               headerTitleAlign: 'center',
               headerRight: () => (
                  <ButtonSaveHeader
                     category="create"
                     disable={selectMember.length > 0 ? false : true}
                     onPress={() => {
                        handleAddMember()
                     }}
                  />
               )
            }}
         />
         <View style={[Styles.p15]}>
            <InputSearch onChange={(val) => setSearch(val)} value={search} />

            {
               selectMember.length > 0
                  ?
                  <View>
                     <ScrollView horizontal style={[Styles.mb10, Styles.pv10]}>
                        {
                           selectMember.map((item: any, index: any) => (
                              <ImageWithLabel
                                 key={index}
                                 label={item.name}
                                 src={`https://wibu-storage.wibudev.com/api/files/${item.img}`}
                                 onClick={() => onChoose(item.idUser, item.name, item.img)}
                              />
                           ))
                        }
                     </ScrollView>
                  </View>

                  :
                  <Text style={[Styles.textDefault, Styles.cGray, Styles.pv05, { textAlign: 'center' }]}>Tidak ada member yang dipilih</Text>
            }
            <ScrollView>

               {
                  data.length > 0 ?
                     data.map((item: any, index: any) => {
                        return (
                           <Pressable
                              key={index}
                              style={[Styles.itemSelectModal]}
                              onPress={() => {
                                 onChoose(item.idUser, item.name, item.img)
                              }}
                           >
                              <View style={[Styles.rowItemsCenter]}>
                                 <ImageUser src={`https://wibu-storage.wibudev.com/api/files/${item.img}`} border />
                                 <View style={[Styles.ml10]}>
                                    <Text style={[Styles.textDefault]}>{item.name}</Text>
                                 </View>
                              </View>
                              {
                                 selectMember.some((i: any) => i.idUser == item.idUser) && <AntDesign name="check" size={20} />
                              }
                           </Pressable>
                        )
                     }
                     )
                     :
                     <Text style={[Styles.textDefault, { textAlign: 'center' }]}>Tidak ada data</Text>
               }
            </ScrollView>
         </View>
      </SafeAreaView>
   )
}