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 ModalSelect from "@/components/modalSelect";
import SelectForm from "@/components/selectForm";
import Styles from "@/constants/Styles";
import { apiGetDivisionReport } from "@/lib/api";
import { stringToDate } from "@/lib/fun_stringToDate";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import dayjs from "dayjs";
import { router, Stack } 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 Report() {
   const { colors } = useTheme();
   const { token, decryptToken } = useAuthSession();
   const [chooseGroup, setChooseGroup] = useState({ val: "", label: "" });
   const [showReport, setShowReport] = useState(false);
   const [isSelect, setSelect] = useState(false);
   const [dataTable, setDataTable] = useState([])
   const [dataChart, setDataChart] = useState({
      progress: [],
      event: [],
      dokumen: [],
   })
   const [data, setData] = useState({
      group: "",
      date: "",
      dateEnd: "",
   });
   const [error, setError] = useState({
      group: false,
      date: false,
      dateEnd: false,
   });

   function validationForm(
      cat: "group" | "date" | "dateEnd",
      val: string,
      label?: string
   ) {
      if (cat == "group") {
         setChooseGroup({ val, label: String(label) });
         setData({ ...data, group: val, dateEnd: "", date: "" });
         if (val == "" || val == "null") {
            setError({ ...error, group: true });
         } else {
            setError({ ...error, group: false });
         }
      } else 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: "undefined",
            date: dayjs(stringToDate(data.date)).format("YYYY-MM-DD"),
            dateEnd: dayjs(stringToDate(data.dateEnd)).format("YYYY-MM-DD"),
            group: chooseGroup.val,
         });
         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: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal mengambil data"

         Toast.show({ type: 'small', text1: message })
      }
   }

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

   return (
      <SafeAreaView style={{ flex: 1, backgroundColor: colors.background }}>
         <Stack.Screen
            options={{
               // headerLeft: () => (
               //    <ButtonBackHeader
               //       onPress={() => {
               //          router.back();
               //       }}
               //    />
               // ),
               headerTitle: "Laporan Divisi",
               headerTitleAlign: "center",
               header: () => (
                  <AppHeader title="Laporan Divisi"
                     showBack={true}
                     onPressLeft={() => router.back()}
                  />
               )
            }}
         />
         <ScrollView
            showsVerticalScrollIndicator={false}
            style={[Styles.h100, { backgroundColor: colors.background }]}
         >
            <View style={[Styles.p15, Styles.mb50]}>
               <SelectForm
                  bg={colors.card}
                  label="Lembaga Desa"
                  placeholder="Pilih Lembaga Desa"
                  value={chooseGroup.label}
                  required
                  onPress={() => {
                     setSelect(true);
                  }}
                  error={error.group}
                  errorText="Lembaga Desa tidak boleh kosong"
               />
               <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>

         <ModalSelect
            category={"group"}
            close={setSelect}
            onSelect={(value) => {
               validationForm("group", value.val, value.label);
            }}
            title={"Lembaga Desa"}
            open={isSelect}
            valChoose={chooseGroup.val}
         />
      </SafeAreaView>
   );
}
