import AppHeader from "@/components/AppHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import { InputForm } from "@/components/inputForm";
import Styles from "@/constants/Styles";
import { apiGetProjectOne, apiReportProject } from "@/lib/api";
import { setUpdateProject } from "@/lib/projectUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
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";
import { useDispatch, useSelector } from "react-redux";

export default function ReportProject() {
   const { token, decryptToken } = useAuthSession();
   const { id } = useLocalSearchParams<{ id: string }>();
   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.projectUpdate)
   const [laporan, setLaporan] = useState("");
   const [error, setError] = useState(false);
   const [disable, setDisable] = useState(false);
   const [loading, setLoading] = useState(false)

   async function handleLoad() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetProjectOne({
            user: hasil,
            cat: "data",
            id: id,
         });
         setLaporan(response.data.report);
      } catch (error) {
         console.error(error);
      }
   }

   useEffect(() => {
      handleLoad();
   }, []);

   function onValidation(val: string) {
      setLaporan(val)
      if (val == "" || val == "null") {
         setError(true)
      } else {
         setError(false)
      }
   }

   function checkAll() {
      if (laporan == "" || laporan == "null" || laporan == null || laporan == undefined || error) {
         setDisable(true)
      } else {
         setDisable(false)
      }
   }

   useEffect(() => {
      checkAll()
   }, [laporan, error]);

   async function handleUpdate() {
      try {
         setLoading(true)
         const hasil = await decryptToken(String(token?.current));
         const response = await apiReportProject({
            report: laporan,
            user: hasil,
         }, id);
         if (response.success) {
            dispatch(setUpdateProject({ ...update, report: !update.report }))
            Toast.show({ type: 'small', text1: 'Berhasil mengubah data', })
            router.back();
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error) {
         console.error(error);
         Toast.show({ type: 'small', text1: 'Terjadi kesalahan', })
      } finally {
         setLoading(false)
      }
   }



   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               // headerLeft: () => (
               //    <ButtonBackHeader
               //       onPress={() => {
               //          router.back();
               //       }}
               //    />
               // ),
               headerTitle: "Laporan Kegiatan",
               headerTitleAlign: "center",
               // headerRight: () => (
               //    <ButtonSaveHeader
               //       disable={disable || loading}
               //       category="update"
               //       onPress={() => { handleUpdate() }}
               //    />
               // ),
               header: () => (
                  <AppHeader
                     title="Laporan Kegiatan"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonSaveHeader
                           disable={disable || loading}
                           category="update"
                           onPress={() => { handleUpdate() }}
                        />
                     }
                  />
               )
            }}
         />
         <ScrollView
            showsVerticalScrollIndicator={false}
            style={[Styles.h100]}
         >
            <View style={[Styles.p15]}>
               <InputForm
                  label="Laporan Kegiatan"
                  type="default"
                  placeholder="Laporan Kegiatan"
                  required
                  bg="white"
                  value={laporan}
                  onChange={(val) => { onValidation(val) }}
                  error={error}
                  errorText="Judul Kegiatan harus diisi"
                  multiline
               />
            </View>
         </ScrollView>
      </SafeAreaView>
   );
}
