import BorderBottomItem from "@/components/borderBottomItem";
import ButtonTab from "@/components/buttonTab";
import InputSearch from "@/components/inputSearch";
import LabelStatus from "@/components/labelStatus";
import PaperGridContent from "@/components/paperGridContent";
import Skeleton from "@/components/skeleton";
import SkeletonTwoItem from "@/components/skeletonTwoItem";
import Text from "@/components/Text";
import { ColorsStatus } from "@/constants/ColorsStatus";
import Styles from "@/constants/Styles";
import { apiGetDivision } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import {
   AntDesign,
   Feather,
   Ionicons,
   MaterialCommunityIcons,
   MaterialIcons,
} from "@expo/vector-icons";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { Pressable, RefreshControl, View, VirtualizedList } from "react-native";
import { useSelector } from "react-redux";

type Props = {
   id: string;
   name: string;
   desc: string;
   jumlah_member: number;
};

export default function ListDivision() {
   const { active, group, cat } = useLocalSearchParams<{
      active?: string;
      group?: string;
      cat?: string;
   }>();
   const [isList, setList] = useState(false);
   const entityUser = useSelector((state: any) => state.user)
   const { token, decryptToken } = useAuthSession()
   const [search, setSearch] = useState("")
   const [nameGroup, setNameGroup] = useState("")
   const [data, setData] = useState<Props[]>([])
   const update = useSelector((state: any) => state.divisionUpdate)
   const arrSkeleton = Array.from({ length: 3 }, (_, index) => index)
   const [loading, setLoading] = useState(false)
   const [status, setStatus] = useState<'true' | 'false'>('true')
   const [category, setCategory] = useState<'divisi-saya' | 'semua'>('divisi-saya')
   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 apiGetDivision({
            user: hasil,
            active: status,
            search: search,
            group: String(group),
            kategori: category,
            page: thisPage
         });

         if (response.success) {
            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)
      }
   }

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

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

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

   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,
      desc: data[index].desc,
      jumlah_member: data[index].jumlah_member,
   })


   return (
      <View style={[Styles.p15, { flex: 1 }]}>
         <View>
            {
               entityUser.role != "user" && entityUser.role != "coadmin" ?
                  <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 == "true" ? "black" : "white"}
                              size={20}
                           />
                        }
                        n={2}
                     />
                  </View>
                  :
                  <View style={[Styles.wrapBtnTab]}>
                     <ButtonTab
                        active={category == "semua" ? "false" : "true"}
                        value="true"
                        onPress={() => { setCategory("divisi-saya") }}
                        label="Divisi Saya"
                        icon={
                           <Ionicons
                              name="file-tray-outline"
                              color={category == "semua" ? "black" : "white"}
                              size={20}
                           />
                        }
                        n={2}
                     />
                     <ButtonTab
                        active={category == "semua" ? "false" : "true"}
                        value="false"
                        onPress={() => { setCategory("semua") }}
                        label="Semua Divisi"
                        icon={
                           <Ionicons
                              name="file-tray-stacked-outline"
                              color={category == "semua" ? "white" : "black"}
                              size={20}
                           />
                        }
                        n={2}
                     />
                  </View>
            }

            <View style={[Styles.rowSpaceBetween, { alignItems: 'center' }]}>
               <InputSearch width={68} onChange={setSearch} />
               <Pressable
                  onPress={() => {
                     setList(!isList);
                  }}
               >
                  <MaterialCommunityIcons
                     name={isList ? "format-list-bulleted" : "view-grid"}
                     color={"black"}
                     size={30}
                  />
               </Pressable>
            </View>
            {(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 ?
                  isList ?
                     arrSkeleton.map((item, index) => (
                        <SkeletonTwoItem key={index} />
                     ))
                     :
                     arrSkeleton.map((item, index) => (
                        <Skeleton key={index} width={100} height={180} widthType="percent" borderRadius={10} />
                     ))
                  :
                  data.length == 0 ? (
                     <View style={[Styles.mt15]}>
                        <Text style={[Styles.textDefault, Styles.cGray, { textAlign: 'center' }]}>Tidak ada data</Text>
                     </View>
                  ) : (
                     isList ? (
                        <View style={[Styles.h100]}>
                           <VirtualizedList
                              data={data}
                              style={[{ paddingBottom: 100 }]}
                              getItemCount={() => data.length}
                              getItem={getItem}
                              renderItem={({ item, index }: { item: Props, index: number }) => {
                                 return (
                                    <BorderBottomItem
                                       key={index}
                                       onPress={() => { router.push(`/division/${item.id}`) }}
                                       borderType="bottom"
                                       icon={
                                          <View style={[Styles.iconContent, ColorsStatus.lightGreen]}>
                                             <MaterialIcons name="group" size={25} color={"#384288"} />
                                          </View>
                                       }
                                       title={item.name}
                                       titleWeight="normal"
                                    />
                                 )
                              }}
                              keyExtractor={(item, index) => String(index)}
                              onEndReached={loadMoreData}
                              onEndReachedThreshold={0.5}
                              showsVerticalScrollIndicator={false}
                              refreshControl={
                                 <RefreshControl
                                    refreshing={refreshing}
                                    onRefresh={handleRefresh}
                                 />
                              }
                           />
                        </View>
                     ) : (
                        <View style={[Styles.h100]}>
                           <VirtualizedList
                              data={data}
                              style={[{ paddingBottom: 100 }]}
                              getItemCount={() => data.length}
                              getItem={getItem}
                              renderItem={({ item, index }: { item: Props, index: number }) => {
                                 return (
                                    <PaperGridContent
                                       key={index}
                                       onPress={() => {
                                          router.push(`/division/${item.id}`);
                                       }}
                                       content="page"
                                       title={item.name}
                                       headerColor="primary"
                                       contentPosition="top"
                                    >
                                       <Text style={[Styles.textDefault]} numberOfLines={2} ellipsizeMode="tail">{item.desc}</Text>
                                    </PaperGridContent>
                                 )
                              }}
                              keyExtractor={(item, index) => String(index)}
                              onEndReached={loadMoreData}
                              onEndReachedThreshold={0.5}
                              showsVerticalScrollIndicator={false}
                              refreshControl={
                                 <RefreshControl
                                    refreshing={refreshing}
                                    onRefresh={handleRefresh}
                                 />
                              }
                           />
                        </View>
                     )
                  )
            }
         </View>
      </View>
   );
}
