import InputSearch from "@/components/inputSearch";
import Skeleton from "@/components/skeleton";
import Text from "@/components/Text";
import { ColorsStatus } from "@/constants/ColorsStatus";
import Styles from "@/constants/Styles";
import { apiGetCalendarHistory } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { FlatList, View, VirtualizedList } from "react-native";

type Props = {
   dateStart: Date
   year: string
   data: []
}
export default function CalendarHistory() {
   const { colors, activeTheme } = useTheme();
   const { id } = useLocalSearchParams<{ id: string }>();
   const { token, decryptToken } = useAuthSession();
   const [data, setData] = useState<Props[]>([])
   const [search, setSearch] = useState('')
   const [loading, setLoading] = useState(true)
   const arrSkeleton = Array.from({ length: 5 })
   const [page, setPage] = useState(1)
   const [waiting, setWaiting] = 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 apiGetCalendarHistory({ user: hasil, search: search, division: id, page: thisPage });
         if (thisPage == 1) {
            setData(response.data)
         } else if (thisPage > 1 && response.data.length > 0) {
            setData([...data, ...response.data])
         } else {
            return;
         }
      } catch (error) {
         console.error(error);
      } finally {
         setLoading(false)
         setWaiting(false)
      }
   }

   useEffect(() => {
      handleLoad(true, 1)
   }, [search])

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

   const getItem = (_data: unknown, index: number): Props => ({
      dateStart: data[index].dateStart,
      year: data[index].year,
      data: data[index].data,
   })

   return (
      <View style={[Styles.p15, { flex: 1, backgroundColor: colors.background }]}>
         <View>
            <InputSearch onChange={(val) => setSearch(val)} />
         </View>
         <View style={[{ flex: 2, }]}>
            {
               loading ?
                  arrSkeleton.map((item, index) => (
                     <Skeleton key={index} width={100} height={60} widthType="percent" borderRadius={10} />
                  ))
                  :
                  <VirtualizedList
                     data={data}
                     getItemCount={() => data.length}
                     getItem={getItem}
                     renderItem={({ item, index }: { item: Props, index: number }) => {
                        return (
                           <View key={index} style={[{ flexDirection: 'row' }, Styles.mv05, activeTheme === 'dark' ? { backgroundColor: colors.card } : ColorsStatus.lightGreen, Styles.p10, Styles.round10, { borderBottomWidth: 1, borderColor: colors.background }]}>
                              <View style={[Styles.mr10, Styles.ph05]}>
                                 <Text style={[Styles.textSubtitle]}>{String(item.dateStart)}</Text>
                                 <Text style={[Styles.textDefault, { textAlign: 'center' }]}>{item.year}</Text>
                              </View>
                              <View style={[{ flex: 1 }]}>
                                 <FlatList data={item.data}
                                    renderItem={({ item, index }: { item: { title: string, timeStart: string, timeEnd: string }, index: number }) => (
                                       <View key={index} style={[Styles.mb05, Styles.w80]}>
                                          <Text style={[Styles.textDefaultSemiBold]} numberOfLines={1} ellipsizeMode="tail">{item.title}</Text>
                                          <Text style={[Styles.textDefault]}>{item.timeStart} | {item.timeEnd}</Text>
                                       </View>
                                    )}
                                    keyExtractor={(item, index) => String(index)}
                                 />
                              </View>
                           </View>
                        )
                     }}
                     keyExtractor={(item, index) => String(index)}
                     onEndReached={loadMoreData}
                     onEndReachedThreshold={0.5}
                     showsVerticalScrollIndicator={false}
                  />
            }
         </View>
      </View>
   )
}