import BorderBottomItem from "@/components/borderBottomItem";
import ButtonTab from "@/components/buttonTab";
import ImageUser from "@/components/imageNew";
import InputSearch from "@/components/inputSearch";
import SkeletonTwoItem from "@/components/skeletonTwoItem";
import Styles from "@/constants/Styles";
import { apiGetUser } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { AntDesign, Feather } from "@expo/vector-icons";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { SafeAreaView, ScrollView, Text, View } from "react-native";
import { useSelector } from "react-redux";

type Props = {
   id: string,
   name: string,
   nik: string,
   email: string,
   phone: string,
   gender: string,
   position: string,
   group: string,
   img: string,
   isActive: boolean,
   role: string
}

export default function Index() {
   const { active, group } = useLocalSearchParams<{ active?: string, group?: string }>()
   const { token, decryptToken } = useAuthSession()
   const entityUser = useSelector((state: any) => state.user)
   const [search, setSearch] = useState('')
   const [nameGroup, setNameGroup] = useState('')
   const [data, setData] = useState<Props[]>([])
   const update = useSelector((state: any) => state.memberUpdate)
   const arrSkeleton = Array.from({ length: 5 }, (_, index) => index)
   const [loading, setLoading] = useState(true)
   const [status, setStatus] = useState<'true' | 'false'>('true')

   async function handleLoad(loading: boolean) {
      try {
         setLoading(loading)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetUser({ user: hasil, active: status, search: search, group: String(group) })
         setData(response.data)
         setNameGroup(response.filter.name)
      } catch (error) {
         console.error(error)
      } finally {
         setLoading(false)
      }
   }

   useEffect(() => {
      handleLoad(true)
   }, [status, search, group])

   useEffect(() => {
      handleLoad(false)
   }, [update])


   return (
      <SafeAreaView>
         <ScrollView>
            <View style={[Styles.p15]}>
               <View style={[Styles.wrapBtnTab]}>
                  <ButtonTab
                     active={status == "false" ? "false" : "true"}
                     value="true"
                     onPress={() => { setStatus("true") }}
                     label="Aktif"
                     icon={<Feather name="check-circle" color={status == "false" ? 'black' : 'white'} size={20} />}
                     n={2} />
                  <ButtonTab
                     active={status == "false" ? "false" : "true"}
                     value="false"
                     onPress={() => { setStatus("false") }}
                     label="Tidak Aktif"
                     icon={<AntDesign name="closecircleo" color={status == "false" ? 'white' : 'black'} size={20} />}
                     n={2} />
               </View>
               <InputSearch onChange={setSearch} />
               {
                  (entityUser.role == "supadmin" || entityUser.role == "developer") &&
                  <View style={[Styles.mv05]}>
                     <Text>Filter : {nameGroup}</Text>
                  </View>
               }
               <View>
                  {
                     loading ?
                        arrSkeleton.map((item, index) => {
                           return (
                              <SkeletonTwoItem key={index} />
                           )
                        })
                        :
                        data.length > 0
                           ?
                           data.map((item, index) => {
                              return (
                                 <BorderBottomItem
                                    key={index}
                                    onPress={() => { router.push(`/member/${item.id}`) }}
                                    borderType="all"
                                    icon={
                                       <ImageUser src={`https://wibu-storage.wibudev.com/api/files/${item.img}`} />
                                    }
                                    title={item.name}
                                    subtitle={`${item.group} - ${item.position}`}
                                 />
                              )
                           })
                           :
                           <Text style={[Styles.textDefault, Styles.cGray, { textAlign: 'center' }]}>Tidak ada data</Text>
                  }
               </View>
            </View>
         </ScrollView>
      </SafeAreaView>
   )
}