import ButtonBackHeader from "@/components/buttonBackHeader";
import HeaderRightCalendarList from "@/components/calendar/headerCalendarList";
import ItemDateCalendar from "@/components/calendar/itemDateCalendar";
import EventItem from "@/components/eventItem";
import Skeleton from "@/components/skeleton";
import Styles from "@/constants/Styles";
import { apiGetCalendarByDateDivision, apiGetIndicatorCalendar } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { Feather } from "@expo/vector-icons";
import dayjs from "dayjs";
import { router, Stack, useLocalSearchParams } from "expo-router";
import moment from "moment";
import { useEffect, useState } from "react";
import { Pressable, SafeAreaView, ScrollView, Text, View } from "react-native";
import Datepicker, {
   CalendarComponents,
   CalendarDay
} from "react-native-ui-datepicker";
import { useSelector } from "react-redux";

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

export default function CalendarDivision() {
   const [selected, setSelected] = useState<any>(new Date());
   const [data, setData] = useState<Props[]>([]);
   const { token, decryptToken } = useAuthSession();
   const { id } = useLocalSearchParams<{ id: string }>();
   const [dataIndicator, setDataIndicator] = useState<any>([]);
   const [month, setMonth] = useState<number>(new Date().getMonth());
   const update = useSelector((state: any) => state.calendarUpdate)
   const [loading, setLoading] = useState(true)


   async function handleLoad(loading: boolean) {
      try {
         setLoading(loading)
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetCalendarByDateDivision({
            user: hasil,
            date: dayjs(selected).format("YYYY-MM-DD"),
            division: id,
         });
         setData(response.data);
      } catch (error) {
         console.error(error);
      } finally {
         setLoading(false)
      }
   }

   async function handleLoadIndicator() {
      try {
         const newDate = new Date(selected?.getFullYear(), month, 1);
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetIndicatorCalendar({
            user: hasil,
            date: dayjs(newDate).format("YYYY-MM-DD"),
            division: id,
         });
         setDataIndicator(response.data);
      } catch (error) {
         console.error(error);
      }
   }

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

   useEffect(() => {
      handleLoad(false);
   }, [update.data]);

   useEffect(() => {
      handleLoadIndicator();
   }, [month, update.data]);

   const components: CalendarComponents = {
      Day: (day: CalendarDay) => {
         const now = String(day.date);
         const today = moment(now).format("YYYY-MM-DD");
         const sign = dataIndicator.includes(today);
         return (
            <ItemDateCalendar
               text={day.text}
               isSelected={day.isSelected}
               isSign={sign}
            />
         );
      },
      IconNext: <Pressable onPress={() => setMonth(month + 1)}>
         <Feather name="chevron-right" size={20} />
      </Pressable>,
      IconPrev: <Pressable onPress={() => setMonth(month - 1)}>
         <Feather name="chevron-left" size={20} />
      </Pressable>,
   };

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => (
                  <ButtonBackHeader
                     onPress={() => {
                        router.back();
                     }}
                  />
               ),
               headerTitle: "Kalender",
               headerTitleAlign: "center",
               headerRight: () => <HeaderRightCalendarList />,
            }}
         />
         <ScrollView>
            <View style={[Styles.p15]}>
               <View style={[Styles.wrapPaper, Styles.p10]}>
                  <Datepicker
                     components={components}
                     mode="single"
                     date={selected}
                     month={month}
                     onChange={({ date }) => setSelected(date)}
                     styles={{
                        selected: Styles.selectedDate,
                     }}


                  />
               </View>
               <View style={[Styles.mb15, Styles.mt15]}>
                  <Text style={[Styles.textDefaultSemiBold, Styles.mb05]}>Acara</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) => (
                                 <EventItem
                                    key={index}
                                    category={index % 2 == 0 ? 'purple' : 'orange'}
                                    title={item.title}
                                    user={item.user_name}
                                    jamAwal={item.timeStart}
                                    jamAkhir={item.timeEnd}
                                    onPress={() => {
                                       router.push(`./calendar/${item.id}`);
                                    }}
                                 />
                              ))
                           ) : (
                              <Text style={[Styles.textDefault, Styles.cGray, { textAlign: 'center' }]}>Tidak ada acara</Text>
                           )
                     }
                  </View>
               </View>
            </View>
         </ScrollView>
      </SafeAreaView>
   );
}
