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 { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiAddMemberTask, apiGetDivisionMember, apiGetTaskOne } from "@/lib/api";
import { setUpdateTask } from "@/lib/taskUpdate";
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, 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 AddMemberTask() {
   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.projectUpdate)
   const { token, decryptToken } = useAuthSession()
   const { id, detail } = useLocalSearchParams<{ id: string, detail: string }>()
   const [dataOld, setDataOld] = useState<Props[]>([])
   const [data, setData] = useState<Props[]>([])
   const [selectMember, setSelectMember] = useState<any[]>([])
   const [search, setSearch] = useState('')
   const [loading, setLoading] = useState(false)

   async function handleLoadOldMember() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetTaskOne({
            user: hasil,
            id: detail,
            cat: 'member',
         });
         setDataOld(response.data)
      } catch (error) {
         console.error(error)
      }
   }


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


   useEffect(() => {
      handleLoadOldMember()
   }, []);


   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 {
         setLoading(true)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiAddMemberTask({ id: detail, data: { user: hasil, member: selectMember, idDivision: id } })
         if (response.success) {
            Toast.show({ type: 'small', text1: 'Berhasil menambahkan anggota', })
            dispatch(setUpdateTask({ ...update, member: !update.member }))
            router.back()
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error) {
         console.error(error)
         Toast.show({ type: 'small', text1: 'Terjadi kesalahan', })
      } finally {
         setLoading(false)
      }
   }


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

            {
               selectMember.length > 0
                  ?
                  <View>
                     <ScrollView horizontal style={[Styles.mb10, Styles.pv10]} showsHorizontalScrollIndicator={false}>
                        {
                           selectMember.map((item: any, index: any) => (
                              <ImageWithLabel
                                 key={index}
                                 label={item.name}
                                 src={`${ConstEnv.url_storage}/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
               showsVerticalScrollIndicator={false}
            >

               {
                  data.length > 0 ?
                     data.map((item: any, index: any) => {
                        const found = dataOld.some((i: any) => i.idUser == item.idUser)
                        return (
                           <Pressable
                              key={index}
                              style={[Styles.itemSelectModal]}
                              onPress={() => {
                                 !found && onChoose(item.idUser, item.name, item.img)
                              }}
                           >
                              <View style={[Styles.rowItemsCenter, Styles.w80]}>
                                 <ImageUser src={`${ConstEnv.url_storage}/files/${item.img}`} border />
                                 <View style={[Styles.ml10]}>
                                    <Text style={[Styles.textDefault]} numberOfLines={1}>{item.name}</Text>
                                    {
                                       found && <Text style={[Styles.textInformation, Styles.cGray]}>sudah menjadi anggota</Text>
                                    }
                                 </View>
                              </View>
                              {
                                 selectMember.some((i: any) => i.idUser == item.idUser) && <AntDesign name="check" size={20} color={'black'} />
                              }
                           </Pressable>
                        )
                     }
                     )
                     :
                     <Text style={[Styles.textDefault, { textAlign: 'center' }]}>Tidak ada data</Text>
               }
            </ScrollView>
         </View>
      </>
   )
}