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 { apiGetUser } from "@/lib/api";
import { setMemberChoose } from "@/lib/memberChoose";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { AntDesign } from "@expo/vector-icons";
import { router, Stack } from "expo-router";
import React, { 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 AddMemberCreateProject() {
   const { colors } = useTheme();
   const dispatch = useDispatch()
   const { token, decryptToken } = useAuthSession()
   const [data, setData] = useState<Props[]>([])
   const [selectMember, setSelectMember] = useState<any[]>([])
   const [search, setSearch] = useState('')
   const entitiesMember = useSelector((state: any) => state.memberChoose)
   const entitiesGroup = useSelector((state: any) => state.groupChoose)
   const entityUser = useSelector((state: any) => state.user)
   const userLogin = useSelector((state: any) => state.entities)

   async function handleLoadMember() {
      const hasil = await decryptToken(String(token?.current))
      let groupFix = userLogin.idGroup
      if (entityUser.role == 'supadmin' || entityUser.role == 'developer') {
         groupFix = entitiesGroup
      }

      const responMemberDivision = await apiGetUser({ user: hasil, active: "true", search: search, group: groupFix })
      setData(responMemberDivision.data.filter((i: any) => i.idUserRole != 'supadmin'))
      if (entitiesMember.length > 0) {
         setSelectMember(entitiesMember)
      }
   }

   useEffect(() => {
      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 isAllSelected = data.length > 0 && data.every((item: any) =>
      selectMember.some((s: any) => s.idUser == item.id)
   )

   function handleSelectAll() {
      if (isAllSelected) {
         setSelectMember([])
      } else {
         const newMembers = data
            .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 {
         dispatch(setMemberChoose(selectMember))
         router.back()
      } catch (error) {
         console.error(error)
         Toast.show({ type: 'small', text1: 'Gagal menambahkan anggota', })
      }
   }


   return (
      <>
         <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()
               //       }}
               //    />
               // )
               header: () => (
                  <AppHeader title="Pilih Anggota"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonSaveHeader
                           category="create"
                           disable={selectMember.length > 0 ? false : true}
                           onPress={() => {
                              handleAddMember()
                           }}
                        />
                     }
                  />
               )
            }}
         />
         <View style={[Styles.p15, Styles.flex1, { backgroundColor: colors.background }]}>
            <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.textCenter, { color: colors.dimmed }, Styles.pv05]}>Tidak ada member yang dipilih</Text>
            }
            <ScrollView
               showsVerticalScrollIndicator={false}
               style={[Styles.h100, Styles.flex1, { backgroundColor: colors.background }]}
            >

               {data.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) => {
                        return (
                           <Pressable
                              key={index}
                              style={[Styles.itemSelectModal, { borderColor: colors.icon + '20' }]}
                              onPress={() => {
                                 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]}>{item.name}</Text>
                                 </View>
                              </View>
                              {
                                 selectMember.some((i: any) => i.idUser == item.id) && <AntDesign name="check" size={20} color={colors.text} />
                              }
                           </Pressable>
                        )
                     }
                     )
                     :
                     <Text style={[Styles.textDefault, Styles.textCenter]}>Tidak ada data</Text>
               }
            </ScrollView>
         </View>
      </>
   )
}