import AppHeader from "@/components/AppHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import { InputForm } from "@/components/inputForm";
import Styles from "@/constants/Styles";
import { apiEditDivision, apiGetDivisionOneDetail } from "@/lib/api";
import { setUpdateDivision } from "@/lib/divisionUpdate";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
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 EditDivision() {
   const { colors } = useTheme();
   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.divisionUpdate)
   const { token, decryptToken } = useAuthSession();
   const { id } = useLocalSearchParams<{ id: string }>();
   const [loading, setLoading] = useState(false)
   const [data, setData] = useState({
      name: "",
      desc: "",
   });
   const [error, setError] = useState({
      name: false,
   });

   async function handleLoad() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetDivisionOneDetail({ user: hasil, id });
         setData({
            name: response.data.division.name,
            desc: response.data.division.desc,
         });
      } catch (error) {
         console.error(error);
      }
   }

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

   async function handleEdit() {
      try {
         setLoading(true)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiEditDivision({ user: hasil, name: data.name, desc: data.desc }, id)
         if (response.success) {
            dispatch(setUpdateDivision(!update))
            Toast.show({ type: 'small', text1: 'Berhasil mengubah data', })
            router.back()
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error: any) {
         console.error(error);
         const message = error?.response?.data?.message || "Gagal mengubah data"

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

   return (
      <SafeAreaView style={{ flex: 1, backgroundColor: colors.background }}>
         <Stack.Screen
            options={{
               // headerLeft: () => (
               //    <ButtonBackHeader
               //       onPress={() => {
               //          router.back();
               //       }}
               //    />
               // ),
               headerTitle: "Edit Divisi",
               headerTitleAlign: "center",
               // headerRight: () => (
               //    <ButtonSaveHeader
               //       disable={error.name || loading ? true : false}
               //       category="update"
               //       onPress={() => { handleEdit() }}
               //    />
               // ),
               header: () => (
                  <AppHeader
                     title="Edit Divisi"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={
                        <ButtonSaveHeader
                           disable={error.name || loading ? true : false}
                           category="update"
                           onPress={() => { handleEdit() }}
                        />
                     }
                  />
               )
            }}
         />
         <ScrollView style={{ backgroundColor: colors.background }}>
            <View style={[Styles.p15, Styles.mb100]}>
               <InputForm
                  label="Nama Divisi"
                  type="default"
                  placeholder="Nama Divisi"
                  required
                  value={data.name}
                  error={error.name}
                  errorText="Nama divisi tidak boleh kosong"
                  onChange={(value) => {
                     setData({ ...data, name: value });
                     if (value == "") {
                        setError({ ...error, name: true });
                     } else {
                        setError({ ...error, name: false });
                     }
                  }}
               />
               <InputForm
                  label="Deskripsi"
                  type="default"
                  placeholder="Deskripsi Divisi"
                  value={data.desc}
                  onChange={(value) => {
                     setData({ ...data, desc: value })
                  }}
                  multiline
               />
            </View>
         </ScrollView>
      </SafeAreaView>
   );
}
