import Styles from "@/constants/Styles";
import { apiGetDataHome } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { useQuery } from "@tanstack/react-query";
import { router } from "expo-router";
import { View } from "react-native";
import EventItem from "../eventItem";
import Skeleton from "../skeleton";
import Text from "../Text";

type Props = {
   id: string
   idDivision: string
   title: string
   desc: string
   status: number
   timeStart: string
   timeEnd: string
   dateStart: string
   dateEnd: string
   createdAt: string
   user_name: string
}

export default function EventHome({ refreshing }: { refreshing: boolean }) {
   const { decryptToken, token } = useAuthSession()
   const { colors } = useTheme();

   // TanStack Query for Event data
   const { data: homeEvents = [], isLoading } = useQuery({
      queryKey: ['homeData', 'event'],
      queryFn: async () => {
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetDataHome({ cat: "event", user: hasil })
         return response.data as Props[]
      },
      enabled: !!token?.current,
      staleTime: 0,
   })

   return (
      <View style={[Styles.mb15]}>
         <Text style={[Styles.textDefaultSemiBold, Styles.mv10]}>Acara Hari Ini</Text>
         <View style={[Styles.wrapPaper, { backgroundColor: colors.card, borderColor: colors.icon + '20' }]}>

            {
               isLoading ?
                  <>
                     <Skeleton width={100} height={70} borderRadius={10} widthType="percent" />
                     <Skeleton width={100} height={70} borderRadius={10} widthType="percent" />
                  </>
                  :
                  homeEvents.length > 0 ?
                     homeEvents.map((item: Props, index: number) => {
                        return (
                           <EventItem key={index} category={index % 2 == 0 ? 'purple' : 'orange'} onPress={() => { router.push(`/division/${item.idDivision}/calendar/${item.id}`) }} title={item.title} user={item.user_name} jamAwal={item.timeStart} jamAkhir={item.timeEnd} />
                        )
                     })
                     : <Text style={[Styles.textDefault, { textAlign: 'center', color: colors.dimmed }]}>Tidak ada acara hari ini</Text>
            }
         </View>
      </View>
   )
}