import AppHeader from "@/components/AppHeader"
import ReportChartDocument from "@/components/division/reportChartDocument"
import ReportChartEvent from "@/components/division/reportChartEvent"
import ReportChartProgress from "@/components/division/reportChartProgress"
import { InputDate } from "@/components/inputDate"
import Styles from "@/constants/Styles"
import { apiGetDivisionReport } from "@/lib/api"
import { stringToDate } from "@/lib/fun_stringToDate"
import { useAuthSession } from "@/providers/AuthProvider"
import dayjs from "dayjs"
import { router, Stack, useLocalSearchParams } from "expo-router"
import { useEffect, useState } from "react"
import { SafeAreaView, ScrollView, View } from "react-native"
import Toast from "react-native-toast-message"

export default function ReportDivision() {
   const { id } = useLocalSearchParams<{ id: string }>()
   const { token, decryptToken } = useAuthSession();
   const [showReport, setShowReport] = useState(false);
   const [dataTable, setDataTable] = useState([])
   const [dataChart, setDataChart] = useState({
      progress: [],
      event: [],
      dokumen: [],
   })
   const [data, setData] = useState({
      date: "",
      dateEnd: "",
   });
   const [error, setError] = useState({
      date: false,
      dateEnd: false,
   });

   function validationForm(cat: "date" | "dateEnd", val: string) {
      if (cat == "date") {
         setData({ ...data, date: val, dateEnd: "" });
         if (val == "" || val == "null") {
            setError({ ...error, date: true, dateEnd: false });
         } else {
            setError({ ...error, date: false, dateEnd: true });
         }
      } else if (cat == "dateEnd") {
         setData({ ...data, dateEnd: val });
         if (val == "" || val == "null") {
            setError({ ...error, dateEnd: true });
         } else {
            setError({ ...error, dateEnd: false });
         }
         const dateEnd = stringToDate(val);
         const date = stringToDate(data.date);
         if (dateEnd < date) {
            setError({ ...error, dateEnd: true });
         } else {
            setError({ ...error, dateEnd: false });
         }
      }
   }

   function checkForm() {
      if (
         Object.values(error).some((v) => v == true) == true ||
         Object.values(data).some((v) => v == "") == true
      ) {
         setShowReport(false);
      } else {
         setShowReport(true);
      }
   }

   useEffect(() => {
      checkForm();
   }, [error, data]);

   async function handleReport() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetDivisionReport({
            user: hasil,
            cat: "lainnya",
            division: id,
            date: dayjs(stringToDate(data.date)).format("YYYY-MM-DD"),
            dateEnd: dayjs(stringToDate(data.dateEnd)).format("YYYY-MM-DD"),
         });
         if (response.success) {
            setDataChart({
               progress: response.data.progress,
               event: response.data.event,
               dokumen: response.data.dokumen,
            })
            setShowReport(true);
         } else {
            Toast.show({ type: 'small', text1: response.message, });
         }
      } catch (error) {
         console.error(error);
      }
   }

   useEffect(() => {
      if (showReport) {
         handleReport();
      }
   }, [showReport]);

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               // headerLeft: () => <ButtonBackHeader onPress={() => { router.back() }} />,
               headerTitle: 'Laporan Divisi',
               headerTitleAlign: 'center',
               header: () => (
                  <AppHeader
                     title="Laporan Divisi"
                     showBack={true}
                     onPressLeft={() => router.back()}
                  />
               )
            }}
         />
         <ScrollView>
            <View style={[Styles.p15, Styles.mb100]}>
               <InputDate
                  onChange={(val) => validationForm("date", val)}
                  mode="date"
                  value={data.date}
                  label="Tanggal Awal"
                  required
                  error={error.date}
                  errorText="Tanggal awal tidak boleh kosong"
                  placeholder="Pilih Tanggal Awal"
               />
               <InputDate
                  onChange={(val) => validationForm("dateEnd", val)}
                  mode="date"
                  value={data.dateEnd}
                  label="Tanggal Akhir"
                  required
                  error={error.dateEnd}
                  errorText="Tanggal akhir tidak boleh kosong atau lebih awal dari tanggal awal"
                  placeholder="Pilih Tanggal Akhir"
               />
               {showReport && (
                  <>
                     <ReportChartProgress data={dataChart.progress} />
                     <ReportChartDocument data={dataChart.dokumen} />
                     <ReportChartEvent data={dataChart.event} />
                  </>
               )}

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