import AppHeader from "@/components/AppHeader";
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 { apiAddMemberDivision, apiGetDivisionOneDetail, apiGetUser } from "@/lib/api";
import { setUpdateDivision } from "@/lib/divisionUpdate";
import { useTheme } from "@/providers/ThemeProvider";
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 AddMemberDivision() {
   const { colors } = useTheme();
   const { token, decryptToken } = useAuthSession()
   const { id } = useLocalSearchParams<{ id: string }>()
   const [dataOld, setDataOld] = useState<Props[]>([])
   const [data, setData] = useState<Props[]>([])
   const [idGroup, setIdGroup] = useState('')
   const [selectMember, setSelectMember] = useState<any[]>([])
   const [search, setSearch] = useState('')
   const update = useSelector((state: any) => state.divisionUpdate)
   const dispatch = useDispatch()
   const [loading, setLoading] = useState(false)

   async function handleLoad() {
      try {
         setLoading(true)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetDivisionOneDetail({ user: hasil, id })
         setDataOld(response.data.member)
         setIdGroup(response.data.division.idGroup)
         const responsemember = await apiGetUser({ user: hasil, active: "true", search: search, group: String(response.data.division.idGroup) })
         setData(responsemember.data.filter((i: any) => i.idUserRole != 'supadmin'))
      } catch (error) {
         console.error(error)
      } finally {
         setLoading(false)
      }
   }

   async function handleLoadMember(search: string) {
      const hasil = await decryptToken(String(token?.current))
      const response = await apiGetUser({ user: hasil, active: "true", search: search, group: String(idGroup) })
      setData(response.data.filter((i: any) => i.idUserRole != 'supadmin'))
   }


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


   function handleSearch(search: string) {
      setSearch(search)
      handleLoadMember(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 }])
      }
   }

   const availableData = data.filter((item: any) => !dataOld.some((i: any) => i.idUser == item.id))
   const isAllSelected = availableData.length > 0 && availableData.every((item: any) =>
      selectMember.some((s: any) => s.idUser == item.id)
   )

   function handleSelectAll() {
      if (isAllSelected) {
         setSelectMember([])
      } else {
         const newMembers = availableData
            .filter((item: any) => !selectMember.some((s: any) => s.idUser == item.id))
            .map((item: any) => ({ idUser: item.id, name: item.name, img: item.img }))
         setSelectMember([...selectMember, ...newMembers])
      }
   }

   async function handleAddMember() {
      try {
         setLoading(true)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiAddMemberDivision({ id: id, data: { user: hasil, member: selectMember } })
         if (response.success) {
            dispatch(setUpdateDivision(!update))
            Toast.show({ type: 'small', text1: 'Berhasil menambahkan anggota', })
            router.replace(`/division/${id}/info`)
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal menambahkan anggota"

         Toast.show({ type: 'small', text1: message })
      } finally {
         setLoading(false)
      }
   }


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

            {
               selectMember.length > 0
                  ?
                  <View>
                     <ScrollView horizontal style={[Styles.mb05, 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.pv05, { textAlign: 'center', color: colors.dimmed }]}>Tidak ada member yang dipilih</Text>
            }
            <ScrollView
               showsVerticalScrollIndicator={false}
            >

               {availableData.length > 0 && (
                  <Pressable
                     style={[Styles.itemSelectModal, { borderColor: colors.icon + '20', paddingTop: 0 }]}
                     onPress={handleSelectAll}
                  >
                     <Text style={[Styles.textMediumSemiBold]}>{isAllSelected ? 'Batalkan Semua' : 'Pilih Semua'}</Text>
                     {isAllSelected && <AntDesign name="check" size={20} color={colors.text} />}
                  </Pressable>
               )}
               {
                  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, { borderBottomColor: colors.icon + '20' }]}
                              onPress={() => {
                                 !found && onChoose(item.id, item.name, item.img)
                              }}
                           >
                              <View style={[Styles.rowItemsCenter]}>
                                 <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, { color: colors.dimmed }]}>sudah menjadi anggota</Text>
                                    }
                                 </View>
                              </View>
                              {
                                 selectMember.some((i: any) => i.idUser == item.id) && <AntDesign name="check" size={20} color={colors.text} />
                              }
                           </Pressable>
                        )
                     }
                     )
                     :
                     <Text style={[Styles.textDefault, { textAlign: 'center' }]}>Tidak ada data</Text>
               }
            </ScrollView>
         </View>
      </>
   )
}