import ButtonBackHeader from "@/components/buttonBackHeader";
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 { router, Stack, useLocalSearchParams } from "expo-router";
import { useEffect, useState } from "react";
import { SafeAreaView, ScrollView, ToastAndroid, View } from "react-native";
import { useDispatch, useSelector } from "react-redux";

export default function EditDivision() {
   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.divisionUpdate)
   const { token, decryptToken } = useAuthSession();
   const { id } = useLocalSearchParams<{ id: string }>();
   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 {
         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))
            ToastAndroid.show('Berhasil mengubah data', ToastAndroid.SHORT)
            router.back()
         } else {
            ToastAndroid.show(response.message, ToastAndroid.SHORT)
         }
      } catch (error) {
         console.error(error)
         ToastAndroid.show('Terjadi kesalahan', ToastAndroid.SHORT)
      }
   }

   return (
      <SafeAreaView>
         <Stack.Screen
            options={{
               headerLeft: () => (
                  <ButtonBackHeader
                     onPress={() => {
                        router.back();
                     }}
                  />
               ),
               headerTitle: "Edit Divisi",
               headerTitleAlign: "center",
               headerRight: () => (
                  <ButtonSaveHeader
                     disable={error.name}
                     category="update"
                     onPress={() => { handleEdit() }}
                  />
               ),
            }}
         />
         <ScrollView>
            <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>
   );
}
