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 ProgressBar from "@/components/progressBar";
import Skeleton from "@/components/skeleton";
import SkeletonTwoItem from "@/components/skeletonTwoItem";
import Text from "@/components/Text";
import WrapTab from "@/components/wrapTab";
import { ColorsStatus } from "@/constants/ColorsStatus";
import Styles from "@/constants/Styles";
import { apiGetProject } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import {
   AntDesign,
   Ionicons,
   MaterialCommunityIcons,
} from "@expo/vector-icons";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useMemo, useState } from "react";
import { Pressable, RefreshControl, ScrollView, View, VirtualizedList } from "react-native";
import { useSelector } from "react-redux";
import AsyncStorage from "@react-native-async-storage/async-storage";

type Props = {
   id: string;
   title: string;
   desc: string;
   status: number;
   member: number;
   progress: number;
   createdAt: string;
};

export default function ListProject() {
   const { status, group, cat, year } = useLocalSearchParams<{
      status?: string;
      group?: string;
      cat?: string;
      year?: string;
   }>();
   const [statusFix, setStatusFix] = useState<'0' | '1' | '2' | '3'>(
      (status == '1' || status == '2' || status == '3') ? status : '0'
   )
   const { token, decryptToken } = useAuthSession();
   const { colors } = useTheme();
   const entityUser = useSelector((state: any) => state.user)
   const [search, setSearch] = useState("")
   const [isList, setList] = useState(false)
   const update = useSelector((state: any) => state.projectUpdate)

   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 queryClient = useQueryClient()
   const [refreshing, setRefreshing] = useState(false)

   // TanStack Query for Projects with Infinite Scroll
   const {
      data,
      fetchNextPage,
      hasNextPage,
      isFetchingNextPage,
      isLoading,
      refetch
   } = useInfiniteQuery({
      queryKey: ['projects', { statusFix, search, group, cat, year }],
      queryFn: async ({ pageParam = 1 }) => {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetProject({
            user: hasil,
            status: statusFix,
            search: search,
            group: String(group),
            kategori: String(cat),
            page: pageParam,
            year: String(year)
         });
         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.data, refetch])

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

   // Get metadata from the first available page
   const nameGroup = useMemo(() => data?.pages[0]?.filter?.name || "", [data])
   const isYear = useMemo(() => data?.pages[0]?.tahun || "", [data])

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

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

   const arrSkeleton = [0, 1, 2]

   const getItem = (_data: unknown, index: number): Props => ({
      id: flatData[index]?.id,
      title: flatData[index]?.title,
      desc: flatData[index]?.desc,
      status: flatData[index]?.status,
      member: flatData[index]?.member,
      progress: flatData[index]?.progress,
      createdAt: flatData[index]?.createdAt,
   })

   return (
      <View style={[Styles.p15, Styles.flex1, { backgroundColor: colors.background }]}>
         <View>
            <WrapTab>
               <ScrollView horizontal showsHorizontalScrollIndicator={false} style={[Styles.round20]}>
                  <ButtonTab
                     active={statusFix}
                     value="0"
                     onPress={() => { setStatusFix("0") }}
                     label="Segera"
                     icon={
                        <MaterialCommunityIcons
                           name="clock-alert-outline"
                           color={statusFix == "0" ? "white" : colors.dimmed}
                           size={20}
                        />
                     }
                     n={4}
                  />
                  <ButtonTab
                     active={statusFix}
                     value="1"
                     onPress={() => { setStatusFix("1") }}
                     label="Dikerjakan"
                     icon={
                        <MaterialCommunityIcons
                           name="progress-check"
                           color={statusFix == "1" ? "white" : colors.dimmed}
                           size={20}
                        />
                     }
                     n={4}
                  />
                  <ButtonTab
                     active={statusFix}
                     value="2"
                     onPress={() => { setStatusFix("2") }}
                     label="Selesai"
                     icon={
                        <Ionicons
                           name="checkmark-done-circle-outline"
                           color={statusFix == "2" ? "white" : colors.dimmed}
                           size={20}
                        />
                     }
                     n={4}
                  />
                  <ButtonTab
                     active={statusFix}
                     value="3"
                     onPress={() => { setStatusFix("3") }}
                     label="Batal"
                     icon={
                        <AntDesign
                           name="closecircleo"
                           color={statusFix == "3" ? "white" : colors.dimmed}
                           size={20}
                        />
                     }
                     n={4}
                  />
               </ScrollView>
            </WrapTab>

            <View style={[Styles.rowSpaceBetween, Styles.rowItemsCenter]}>
               <InputSearch width={68} onChange={setSearch} />
               <Pressable onPress={toggleView}>
                  <MaterialCommunityIcons
                     name={isList ? "format-list-bulleted" : "view-grid"}
                     color={colors.text}
                     size={30}
                  />
               </Pressable>
            </View>
            <View style={[Styles.mt10]}>
               {
                  <View style={[Styles.rowOnly]}>
                     <Text style={[Styles.mr05]}>Filter :</Text>
                     {
                        (entityUser.role == "supadmin" || entityUser.role == "developer") &&
                        <LabelStatus size="small" category="secondary" text={nameGroup} style={[Styles.mr05]} />
                     }
                     {
                        (entityUser.role == 'user' || entityUser.role == 'coadmin')
                           ? (cat == 'null' || cat == 'undefined' || cat == undefined || cat == '' || cat == 'data-saya') ? <LabelStatus size="small" category="secondary" text="Kegiatan Saya" style={[Styles.mr05]} /> : <LabelStatus size="small" category="secondary" text="Semua Kegiatan" style={[Styles.mr05]} />
                           : ''
                     }
                     <LabelStatus size="small" category="secondary" text={isYear} style={[Styles.mr05]} />
                  </View>
               }
            </View>
         </View>
         <View style={[Styles.flex2, 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
                     ?
                     isList ? (
                        <View style={[Styles.h100]}>
                           <VirtualizedList
                              data={flatData}
                              getItemCount={() => flatData.length}
                              getItem={getItem}
                              renderItem={({ item, index }: { item: Props, index: number }) => {
                                 return (
                                    <BorderBottomItem
                                       key={index}
                                       onPress={() => { router.push(`/project/${item.id}`); }}
                                       borderType="bottom"
                                       bgColor="transparent"
                                       icon={
                                          <View style={[Styles.iconContent]} >
                                             <AntDesign
                                                name="areachart"
                                                size={25}
                                                color={"black"}
                                             />
                                          </View>
                                       }
                                       title={item.title}
                                    />
                                 );
                              }}
                              keyExtractor={(item, index) => index.toString()}
                              onEndReached={loadMoreData}
                              onEndReachedThreshold={0.5}
                              showsVerticalScrollIndicator={false}
                              refreshControl={
                                 <RefreshControl
                                    refreshing={refreshing}
                                    onRefresh={handleRefresh}
                                    tintColor={colors.icon}
                                 />
                              }
                           />
                        </View>
                     ) : (
                        <View style={[Styles.h100]}>
                           <VirtualizedList
                              data={flatData}
                              getItemCount={() => flatData.length}
                              getItem={getItem}
                              renderItem={({ item, index }: { item: Props, index: number }) => {
                                 return (
                                    <PaperGridContent
                                       key={index}
                                       onPress={() => {
                                          router.push(`/project/${item.id}`);
                                       }}
                                       content="page"
                                       title={item.title}
                                       headerColor="primary"
                                       titleTail={2}
                                    >
                                       <ProgressBar value={item.progress} category="list" />
                                       <View style={[Styles.rowSpaceBetween]}>
                                          <Text style={[Styles.textDefault, { color: colors.dimmed }]}>
                                             {item.createdAt}
                                          </Text>
                                          <LabelStatus
                                             size="default"
                                             category={
                                                item.status === 0 ? 'secondary' :
                                                   item.status === 1 ? 'warning' :
                                                      item.status === 2 ? 'success' :
                                                         item.status === 3 ? 'error' :
                                                            'secondary'
                                             }
                                             text={
                                                item.status === 0 ? 'SEGERA' :
                                                   item.status === 1 ? 'DIKERJAKAN' :
                                                      item.status === 2 ? 'SELESAI' :
                                                         item.status === 3 ? 'DIBATALKAN' :
                                                            'SEGERA'
                                             }
                                          />
                                       </View>
                                    </PaperGridContent>
                                 );
                              }}
                              keyExtractor={(item, index) => index.toString()}
                              onEndReached={loadMoreData}
                              onEndReachedThreshold={0.5}
                              showsVerticalScrollIndicator={false}
                              refreshControl={
                                 <RefreshControl
                                    refreshing={refreshing}
                                    onRefresh={handleRefresh}
                                    tintColor={colors.icon}
                                 />
                              }
                           />
                        </View>
                     )
                     :
                     <View style={[Styles.mt15]}>
                        <Text style={[Styles.textDefault, Styles.textCenter, { color: colors.dimmed }]}>Tidak ada kegiatan</Text>
                     </View>
            }
         </View>
      </View>
   );
}
