import AppHeader from "@/components/AppHeader";
import HeaderRightCalendarList from "@/components/calendar/headerCalendarList";
import ItemDateCalendar from "@/components/calendar/itemDateCalendar";
import EventItem from "@/components/eventItem";
import Skeleton from "@/components/skeleton";
import Text from "@/components/Text";
import Styles from "@/constants/Styles";
import { apiGetCalendarByDateDivision, apiGetIndicatorCalendar } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { Feather } from "@expo/vector-icons";
import { router, Stack, useLocalSearchParams } from "expo-router";
import 'intl';
import 'intl/locale-data/jsonp/id';
import moment from "moment";
import { useEffect, useState } from "react";
import { Pressable, RefreshControl, SafeAreaView, ScrollView, 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 { colors, activeTheme } = useTheme();
   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)
   const [loadingBtn, setLoadingBtn] = useState(false)
   const [refreshing, setRefreshing] = useState(false)


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

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

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

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

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

   const handleRefresh = async () => {
      setRefreshing(true)
      handleLoad(false)
      await new Promise(resolve => setTimeout(resolve, 2000));
      setRefreshing(false)
   };

   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}
               onPress={() => setSelected(new Date(today))}
            />
         );
      },
      IconNext: <Pressable onPress={() => !loadingBtn ? setMonth(month + 1) : null}>
         <Feather name="chevron-right" size={20} color={loadingBtn ? 'gray' : colors.text} />
      </Pressable>,
      IconPrev: <Pressable onPress={() => !loadingBtn ? setMonth(month - 1) : null}>
         <Feather name="chevron-left" size={20} color={loadingBtn ? 'gray' : colors.text} />
      </Pressable>,
   };

   return (
      <SafeAreaView style={{ flex: 1, backgroundColor: colors.background }}>
         <Stack.Screen
            options={{
               // headerLeft: () => (
               //    <ButtonBackHeader
               //       onPress={() => {
               //          router.back();
               //       }}
               //    />
               // ),
               headerTitle: "Kalender",
               headerTitleAlign: "center",
               // headerRight: () => <HeaderRightCalendarList />,
               header: () => (
                  <AppHeader
                     title="Kalender"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={<HeaderRightCalendarList />}
                  />
               )
            }}
         />
         <ScrollView
            refreshControl={
               <RefreshControl
                  refreshing={refreshing}
                  onRefresh={handleRefresh}
               />
            }
            style={[Styles.h100]}
         >
            <View style={[Styles.p15]}>
               <View style={[Styles.wrapPaper, Styles.p10, { backgroundColor: colors.card, borderColor: colors.background }]}>
                  <Datepicker
                     components={components}
                     mode="single"
                     date={selected}
                     month={month}
                     onMonthChange={(month) => setMonth(month)}
                     styles={{
                        selected: Styles.selectedDate,
                        month_label: { color: colors.text },
                        month_selector_label: { color: colors.text },
                        year_label: { color: colors.text },
                        year_selector_label: { color: colors.text },
                        day_label: { color: colors.text },
                        time_label: { color: colors.text },
                        weekday_label: { color: colors.text },
                     }}
                  />
               </View>
               <View style={[Styles.mb15, Styles.mt15]}>
                  <Text style={[Styles.textDefaultSemiBold, Styles.mb05]}>Acara</Text>
                  <View style={[Styles.wrapPaper, { backgroundColor: colors.card, borderColor: colors.background }]}>
                     {
                        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, { textAlign: 'center', color: colors.dimmed }]}>Tidak ada acara</Text>
                           )
                     }
                  </View>
               </View>
            </View>
         </ScrollView>
      </SafeAreaView>
   );
}
