import BorderBottomItem from "@/components/borderBottomItem";
import ButtonTab from "@/components/buttonTab";
import InputSearch from "@/components/inputSearch";
import LabelStatus from "@/components/labelStatus";
import SkeletonContent from "@/components/skeletonContent";
import Text from "@/components/Text";
import WrapTab from "@/components/wrapTab";
import { ColorsStatus } from "@/constants/ColorsStatus";
import Styles from "@/constants/Styles";
import { apiGetDiscussionGeneral } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { AntDesign, Feather, Ionicons, MaterialIcons } 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
   title: string
   desc: string
   status: number
   total_komentar: number
   createdAt: string
}

export default function Discussion() {
   const entityUser = useSelector((state: any) => state.user)
   const { token, decryptToken } = useAuthSession()
   const { colors } = useTheme();
   const { active, group } = useLocalSearchParams<{ active?: string, group?: string }>()
   const [search, setSearch] = useState('')
   const update = useSelector((state: any) => state.discussionGeneralDetailUpdate)
   const queryClient = useQueryClient()
   const [status, setStatus] = useState<'true' | 'false'>(active == 'false' ? 'false' : 'true')
   const [refreshing, setRefreshing] = useState(false)

   // TanStack Query for Discussions with Infinite Scroll
   const {
      data,
      fetchNextPage,
      hasNextPage,
      isFetchingNextPage,
      isLoading,
      refetch
   } = useInfiniteQuery({
      queryKey: ['discussions', { status, search, group }],
      queryFn: async ({ pageParam = 1 }) => {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetDiscussionGeneral({ 
            user: hasil, 
            active: status, 
            search: 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: ['discussions'] })
      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,
      title: flatData[index]?.title,
      desc: flatData[index]?.desc,
      status: flatData[index]?.status,
      total_komentar: flatData[index]?.total_komentar,
      createdAt: flatData[index]?.createdAt,
   })

   return (
      <View style={[Styles.p15, Styles.flex1, { 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="Arsip"
                     icon={<AntDesign name="closecircleo" color={status == "true" ? colors.dimmed : 'white'} size={20} />}
                     n={2} />
               </WrapTab>
            }

            <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={[Styles.flex2, Styles.mt05]}>
            {
               isLoading ?
                  arrSkeleton.map((item: any, i: number) => {
                     return (
                        <SkeletonContent key={i} />
                     )
                  })
                  :
                  flatData.length > 0
                     ?
                     <VirtualizedList
                        data={flatData}
                        getItemCount={() => flatData.length}
                        getItem={getItem}
                        renderItem={({ item, index }: { item: Props, index: number }) => {
                           return (
                              <BorderBottomItem
                                 bgColor="transparent"
                                 key={index}
                                 onPress={() => { router.push(`/discussion/${item.id}`) }}
                                 borderType="bottom"
                                 icon={
                                    <MaterialIcons name="chat" size={25} color={colors.text} />
                                 }
                                 title={item.title}
                                 subtitle={
                                    status != "false" && <LabelStatus category={item.status === 1 ? "success" : "error"} text={item.status === 1 ? "BUKA" : "TUTUP"} size="small" />
                                 }
                                 rightTopInfo={item.createdAt}
                                 desc={item.desc?.replace(/<[^>]*>?/gm, ' ').replace(/\r?\n|\r/g, ' ')}
                                 leftBottomInfo={
                                    <View style={[Styles.rowItemsCenter]}>
                                       <Ionicons name="chatbox-ellipses-outline" size={18} color={colors.dimmed} style={Styles.mr05} />
                                       <Text style={[Styles.textInformation, { color: colors.dimmed }, Styles.mb05]}>Diskusikan</Text>
                                    </View>
                                 }
                                 rightBottomInfo={`${item.total_komentar} Komentar`}

                              />
                           )
                        }}
                        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, Styles.textCenter, { color: colors.dimmed }]}>Tidak ada data</Text>
            }
         </View>
      </View>
   );
}