import ButtonBackHeader from "@/components/buttonBackHeader";
import ItemHistoryEvent from "@/components/calendar/itemHistoryEvent";
import InputSearch from "@/components/inputSearch";
import Skeleton from "@/components/skeleton";
import Styles from "@/constants/Styles";
import { apiGetCalendarHistory } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { router, Stack, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { SafeAreaView, ScrollView, View } from "react-native";

type Props = {
   dateStart: Date
   year: string
   data: []
}
export default function CalendarHistory() {
   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 })

   async function handleLoad() {
      try {
         setLoading(true)
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetCalendarHistory({ user: hasil, search: search, division: id });
         setData(response.data);
      } catch (error) {
         console.error(error);
      } finally {
         setLoading(false)
      }
   }

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

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Riwayat Acara',
               headerTitleAlign: 'center',
            }}
         />
         <ScrollView>
            <View style={[Styles.p15]}>
               <InputSearch onChange={(val) => setSearch(val)} />
               {
                  loading ?
                     arrSkeleton.map((item, index) => (
                        <Skeleton key={index} width={100} height={60} widthType="percent" borderRadius={10} />
                     ))
                     :
                     <ItemHistoryEvent data={data} />
               }

            </View>
         </ScrollView>
      </SafeAreaView>
   )
}