import BorderBottomItem from "@/components/borderBottomItem";
import ButtonTab from "@/components/buttonTab";
import ImageUser from "@/components/imageNew";
import InputSearch from "@/components/inputSearch";
import LabelStatus from "@/components/labelStatus";
import SkeletonTwoItem from "@/components/skeletonTwoItem";
import Text from "@/components/Text";
import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiGetUser } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { AntDesign, Feather } from "@expo/vector-icons";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { RefreshControl, View, VirtualizedList } 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 { colors } = useTheme();
   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')
   const [page, setPage] = useState(1)
   const [waiting, setWaiting] = useState(false)
   const [refreshing, setRefreshing] = useState(false)

   async function handleLoad(loading: boolean, thisPage: number) {
      try {
         setWaiting(true)
         setLoading(loading)
         setPage(thisPage)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetUser({ user: hasil, active: status, search, group: String(group), page: thisPage })
         if (thisPage == 1) {
            setData(response.data)
         } else if (thisPage > 1 && response.data.length > 0) {
            setData([...data, ...response.data])
         } else {
            return;
         }
         setNameGroup(response.filter.name)
      } catch (error) {
         console.error(error)
      } finally {
         setLoading(false)
         setWaiting(false)
      }
   }

   const loadMoreData = () => {
      if (waiting) return
      setTimeout(() => {
         handleLoad(false, page + 1)
      }, 1000);
   };

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

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

   const handleRefresh = async () => {
      setRefreshing(true)
      handleLoad(false, 1)
      await new Promise(resolve => setTimeout(resolve, 2000));
      setRefreshing(false)
   };

   const getItem = (_data: unknown, index: number): Props => ({
      id: data[index].id,
      name: data[index].name,
      nik: data[index].nik,
      email: data[index].email,
      phone: data[index].phone,
      gender: data[index].gender,
      position: data[index].position,
      group: data[index].group,
      img: data[index].img,
      isActive: data[index].isActive,
      role: data[index].role,
   });

   return (
      <View style={[Styles.p15, { flex: 1, backgroundColor: colors.background }]}>
         <View>
            <View style={[Styles.wrapBtnTab, { backgroundColor: colors.card }]}>
               <ButtonTab
                  active={status == "false" ? "false" : "true"}
                  value="true"
                  onPress={() => { setStatus("true") }}
                  label="Aktif"
                  icon={<Feather name="check-circle" color={status == "false" ? colors.text : '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' : colors.text} size={20} />}
                  n={2} />
            </View>
            <InputSearch onChange={setSearch} />
            {
               (entityUser.role == "supadmin" || entityUser.role == "developer") &&
               <View style={[Styles.mv05, Styles.rowOnly]}>
                  <Text>Filter :</Text>
                  <LabelStatus size="small" category="secondary" text={nameGroup} style={[Styles.mh05]} />
               </View>
            }
         </View>
         <View style={[{ flex: 2 }, Styles.mt05]}>
            {
               loading ?
                  arrSkeleton.map((item, index) => {
                     return (
                        <SkeletonTwoItem key={index} />
                     )
                  })
                  :
                  data.length > 0
                     ?
                     <VirtualizedList
                        data={data}
                        getItemCount={() => data.length}
                        getItem={getItem}
                        renderItem={({ item, index }: { item: Props, index: number }) => {
                           return (
                              <BorderBottomItem
                                 key={index}
                                 onPress={() => { router.push(`/member/${item.id}`) }}
                                 borderType="all"
                                 icon={
                                    <ImageUser src={`${ConstEnv.url_storage}/files/${item.img}`} />
                                 }
                                 title={item.name}
                                 subtitle={`${item.group} - ${item.position}`}
                              />
                           )
                        }}
                        keyExtractor={(item, index) => String(index)}
                        onEndReached={loadMoreData}
                        onEndReachedThreshold={0.5}
                        showsVerticalScrollIndicator={false}
                        refreshControl={
                           <RefreshControl
                              refreshing={refreshing}
                              onRefresh={handleRefresh}
                              tintColor={colors.primary}
                           />
                        }
                     />
                     :
                     <Text style={[Styles.textDefault, Styles.cGray, { textAlign: 'center' }]}>Tidak ada data</Text>
            }
         </View>
      </View>
   )
}