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 WrapTab from "@/components/wrapTab";
import Styles from "@/constants/Styles";
import { apiGetDivision } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import {
   AntDesign,
   Feather,
   Ionicons,
   MaterialCommunityIcons
} from "@expo/vector-icons";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useMemo, 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);

   useEffect(() => {
      AsyncStorage.getItem('division_view_mode').then((val) => {
         if (val !== null) setList(val === 'list')
      })
   }, [])

   function toggleView() {
      const next = !isList
      setList(next)
      AsyncStorage.setItem('division_view_mode', next ? 'list' : 'grid')
   }
   const entityUser = useSelector((state: any) => state.user)
   const { token, decryptToken } = useAuthSession()
   const { colors } = useTheme();
   const [search, setSearch] = useState("")
   const queryClient = useQueryClient()
   const [status, setStatus] = useState<'true' | 'false'>(active == 'false' ? 'false' : 'true')
   const [category, setCategory] = useState<'divisi-saya' | 'semua'>(cat == 'semua' ? 'semua' : 'divisi-saya')
   const update = useSelector((state: any) => state.divisionUpdate)
   const [refreshing, setRefreshing] = useState(false)

   // TanStack Query for Divisions with Infinite Scroll
   const {
      data,
      fetchNextPage,
      hasNextPage,
      isFetchingNextPage,
      isLoading,
      refetch
   } = useInfiniteQuery({
      queryKey: ['divisions', { status, search, group, category }],
      queryFn: async ({ pageParam = 1 }) => {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetDivision({
            user: hasil,
            active: status,
            search: search,
            group: String(group),
            kategori: category,
            page: pageParam
         });
         return response;
      },
      initialPageParam: 1,
      getNextPageParam: (lastPage, allPages) => {
         return lastPage.data.length > 0 ? allPages.length + 1 : undefined;
      },
      enabled: !!token?.current,
      staleTime: 0,
   })

   // Refetch when manual update state changes
   useEffect(() => {
      refetch()
   }, [update, refetch])

   // Flatten pages into a single data array
   const flatData = useMemo(() => {
      return data?.pages.flatMap(page => page.data) || [];
   }, [data])

   // Get nameGroup from the first available page
   const nameGroup = useMemo(() => {
      return data?.pages[0]?.filter?.name || "";
   }, [data])

   const handleRefresh = async () => {
      setRefreshing(true)
      await queryClient.invalidateQueries({ queryKey: ['divisions'] })
      setRefreshing(false)
   };

   const loadMoreData = () => {
      if (hasNextPage && !isFetchingNextPage) {
         fetchNextPage()
      }
   };

   const arrSkeleton = [0, 1, 2]

   const getItem = (_data: unknown, index: number): Props => ({
      id: flatData[index]?.id,
      name: flatData[index]?.name,
      desc: flatData[index]?.desc,
      jumlah_member: flatData[index]?.jumlah_member,
   })


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

            <View style={[Styles.rowSpaceBetween, { alignItems: 'center' }]}>
               <InputSearch width={68} onChange={setSearch} />
               <Pressable onPress={toggleView}>
                  <MaterialCommunityIcons
                     name={isList ? "format-list-bulleted" : "view-grid"}
                     color={colors.text}
                     size={30}
                  />
               </Pressable>
            </View>
            {(entityUser.role == "supadmin" || entityUser.role == "developer") && (
               <View style={[Styles.mt10, Styles.rowOnly]}>
                  <Text>Filter :</Text>
                  <LabelStatus size="small" category="secondary" text={nameGroup} style={[Styles.mh05]} />
               </View>
            )}
         </View>
         <View style={[{ flex: 2 }, Styles.mt10]}>
            {
               isLoading ?
                  isList ?
                     arrSkeleton.map((item, index) => (
                        <SkeletonTwoItem key={index} />
                     ))
                     :
                     arrSkeleton.map((item, index) => (
                        <Skeleton key={index} width={100} height={180} widthType="percent" borderRadius={10} />
                     ))
                  :
                  flatData.length == 0 ? (
                     <View style={[Styles.mt15]}>
                        <Text style={[Styles.textDefault, { textAlign: 'center', color: colors.dimmed }]}>Tidak ada data</Text>
                     </View>
                  ) : (
                     isList ? (
                        <View style={[Styles.h100]}>
                           <VirtualizedList
                              data={flatData}
                              style={[{ paddingBottom: 100 }]}
                              getItemCount={() => flatData.length}
                              getItem={getItem}
                              renderItem={({ item, index }: { item: Props, index: number }) => {
                                 return (
                                    <BorderBottomItem
                                       key={index}
                                       onPress={() => { router.push(`/division/${item.id}`) }}
                                       borderType="bottom"
                                       bgColor="transparent"
                                       icon={
                                          <View style={[Styles.iconContent]}>
                                             <Feather name="users" size={25} color={'black'} />
                                          </View>
                                       }
                                       title={item.name}
                                    />
                                 )
                              }}
                              keyExtractor={(item, index) => String(index)}
                              onEndReached={loadMoreData}
                              onEndReachedThreshold={0.5}
                              showsVerticalScrollIndicator={false}
                              refreshControl={
                                 <RefreshControl
                                    refreshing={refreshing}
                                    onRefresh={handleRefresh}
                                    tintColor={colors.icon}
                                 />
                              }
                           />
                        </View>
                     ) : (
                        <View style={[Styles.h100]}>
                           <VirtualizedList
                              data={flatData}
                              style={[{ paddingBottom: 100 }]}
                              getItemCount={() => flatData.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}
                                    tintColor={colors.icon}
                                 />
                              }
                           />
                        </View>
                     )
                  )
            }
         </View>
      </View>
   );
}
