import Styles from "@/constants/Styles";
import { apiGetDataHome } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { router } from "expo-router";
import { useEffect, useState } from "react";
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 [data, setData] = useState<Props[]>([])
   const [loading, setLoading] = useState(true)

   async function handleData(loading: boolean) {
      try {
         setLoading(loading)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiGetDataHome({ cat: "event", user: hasil })
         setData(response.data)
      } catch (error) {
         console.error(error)
      } finally {
         setLoading(false)
      }
   }

   useEffect(() => {
      if (refreshing)
         handleData(false)
   }, [refreshing]);

   useEffect(() => {
      handleData(true)
   }, []);

   return (
      <View style={[Styles.mb15]}>
         <Text style={[Styles.textDefaultSemiBold, Styles.mv10]}>Acara Hari Ini</Text>
         <View style={[Styles.wrapPaper]}>

            {
               loading ?
                  <>
                     <Skeleton width={100} height={70} borderRadius={10} widthType="percent" />
                     <Skeleton width={100} height={70} borderRadius={10} widthType="percent" />
                  </>
                  :
                  data.length > 0 ?
                     data.map((item, index) => {
                        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, Styles.cGray, { textAlign: 'center' }]}>Tidak ada acara hari ini</Text>
            }
         </View>
      </View>
   )
}