import AppHeader from "@/components/AppHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import { InputForm } from "@/components/inputForm";
import Styles from "@/constants/Styles";
import { apiCancelProject } from "@/lib/api";
import { setUpdateProject } from "@/lib/projectUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { router, Stack, useLocalSearchParams } from "expo-router";
import React, { 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 ProjectCancel() {
   const { colors } = useTheme();
   const { token, decryptToken } = useAuthSession();
   const { id } = useLocalSearchParams<{ id: string }>();
   const dispatch = useDispatch();
   const update = useSelector((state: any) => state.projectUpdate);
   const [reason, setReason] = useState("");
   const [error, setError] = useState(false);
   const [disable, setDisable] = useState(false);
   const [loading, setLoading] = useState(false)


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

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

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

   async function handleCancel() {
      try {
         setLoading(true)
         const hasil = await decryptToken(String(token?.current));
         const response = await apiCancelProject({
            reason: reason,
            user: hasil,
         }, id);
         if (response.success) {
            dispatch(setUpdateProject({ ...update, data: !update.data }))
            Toast.show({ type: 'small', text1: 'Berhasil membatalkan kegiatan', })
            router.back();
         }
      } catch (error : any ) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal membatalkan kegiatan"

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

   return (
      <SafeAreaView style={[Styles.flex1, { backgroundColor: colors.background }]}>
         <Stack.Screen
            options={{
               // headerLeft: () => (
               //    <ButtonBackHeader
               //       onPress={() => {
               //          router.back();
               //       }}
               //    />
               // ),
               headerTitle: "Pembatalan Kegiatan",
               headerTitleAlign: "center",
               // headerRight: () => (
               //    <ButtonSaveHeader
               //       disable={disable || loading}
               //       category="cancel"
               //       onPress={() => {
               //          handleCancel();
               //       }}
               //    />
               // ),
               header: () => (
                  <AppHeader
                     title="Pembatalan Kegiatan"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonSaveHeader
                           disable={disable || loading}
                           category="cancel"
                           onPress={() => {
                              handleCancel();
                           }}
                        />
                     }
                  />
               )
            }}
         />
         <ScrollView
            showsVerticalScrollIndicator={false}
            style={[Styles.h100, { backgroundColor: colors.background }]}
         >
            <View style={[Styles.p15]}>
               <InputForm
                  label="Alasan Pembatalan"
                  type="default"
                  placeholder="Alasan Pembatalan"
                  required
                  bg={colors.card}
                  error={error}
                  errorText="Alasan pembatalan harus diisi"
                  onChange={(val) => onValidation(val)}
                  multiline
               />
            </View>
         </ScrollView>
      </SafeAreaView>
   );
}
