import AppHeader from "@/components/AppHeader";
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 { useTheme } from "@/providers/ThemeProvider";
import { AntDesign } from "@expo/vector-icons";
import { StackActions, useNavigation } from "@react-navigation/native";
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 CreateDivisionAddAdmin() {
   const { colors } = useTheme();
   const { token, decryptToken } = useAuthSession()
   const navigation = useNavigation()
   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))
            navigation.dispatch(StackActions.pop(3))
            // router.replace(`/division/`)
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error : any ) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal menambahkan data"

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


   return (
      <>
         <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()
               //       }}
               //    />
               // )
               header: () => (
                  <AppHeader title="Pilih Admin Divisi"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={<ButtonSaveHeader
                        category="create"
                        disable={selectMember.length == 0 || loading ? true : false}
                        onPress={() => {
                           handleAddMember()
                        }}
                     />}
                  />
               )
            }}
         />
         <View style={[Styles.p15, { flex: 1, backgroundColor: colors.background }]}>
            <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, { borderBottomColor: colors.icon + '20' }]}
                              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, { color: colors.dimmed }]}>sudah menjadi anggota</Text>
                                    }
                                 </View>
                              </View>
                              {
                                 selectMember.some((i: any) => i == item.idUser) && <AntDesign name="check" size={20} color={colors.text} />
                              }
                           </Pressable>
                        )
                     }
                     )
                     :
                     <Text style={[Styles.textDefault, { textAlign: 'center' }]}>Tidak ada data</Text>
               }
            </ScrollView>
         </View>
      </>
   )
}