import GuideOverlay from "@/components/GuideOverlay";
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 WrapTab from "@/components/wrapTab";
import { ConstEnv } from "@/constants/ConstEnv";
import Styles from "@/constants/Styles";
import { apiGetUser } from "@/lib/api";
import { GUIDE_MEMBER } from "@/lib/guideSteps";
import { useGuide } from "@/lib/useGuide";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { AntDesign, Feather } from "@expo/vector-icons";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useMemo, 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 update = useSelector((state: any) => state.memberUpdate)
   const queryClient = useQueryClient()
   const [status, setStatus] = useState<'true' | 'false'>(active == 'false' ? 'false' : 'true')
   const [refreshing, setRefreshing] = useState(false)
   const { visible: guideVisible, dismiss: dismissGuide } = useGuide('member')

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

   // 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])

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

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

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

   const arrSkeleton = [0, 1, 2, 3, 4]

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

   return (
      <View style={[Styles.p15, { flex: 1, backgroundColor: colors.background }]}>
         <GuideOverlay visible={guideVisible} steps={GUIDE_MEMBER} onDismiss={dismissGuide} />
         <View>
            <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 == "false" ? 'white' : colors.dimmed} size={20} />}
                  n={2} />
            </WrapTab>
            <InputSearch onChange={setSearch} />
            {
               (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 ?
                  arrSkeleton.map((item, index) => {
                     return (
                        <SkeletonTwoItem key={index} />
                     )
                  })
                  :
                  flatData.length > 0
                     ?
                     <VirtualizedList
                        data={flatData}
                        getItemCount={() => flatData.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.icon}
                           />
                        }
                     />
                     :
                     <Text style={[Styles.textDefault, { textAlign: 'center', color: colors.dimmed }]}>Tidak ada data</Text>
            }
         </View>
      </View>
   )
}