import ButtonBackHeader from "@/components/buttonBackHeader";
import ButtonSaveHeader from "@/components/buttonSaveHeader";
import { InputForm } from "@/components/inputForm";
import Styles from "@/constants/Styles";
import { apiEditDiscussionGeneral, apiGetDiscussionGeneralOne } from "@/lib/api";
import { setUpdateDiscussionGeneralDetail } from "@/lib/discussionGeneralDetail";
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 EditDiscussionGeneral() {
   const { token, decryptToken } = useAuthSession();
   const { id } = useLocalSearchParams<{ id: string }>();
   const [disableBtn, setDisableBtn] = useState(false)
   const dispatch = useDispatch()
   const [loading, setLoading] = useState(false)
   const update = useSelector((state: any) => state.discussionGeneralDetailUpdate)
   const [dataForm, setDataForm] = useState({
      title: "",
      desc: "",
   });
   const [error, setError] = useState({
      title: false,
      desc: false,
   })

   async function handleLoad() {
      try {
         const hasil = await decryptToken(String(token?.current));
         const response = await apiGetDiscussionGeneralOne({
            id: id,
            user: hasil,
            cat: "detail",
         });
         if (response.success) {
            setDataForm(response.data);
         }
      } catch (error) {
         console.error(error);
      }
   }


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

   function validationForm(cat: string, val: any) {
      if (cat == "title") {
         setDataForm({ ...dataForm, title: val });
         if (val == "" || val == "null") {
            setError({ ...error, title: true });
         } else {
            setError({ ...error, title: false });
         }
      } else if (cat == "desc") {
         setDataForm({ ...dataForm, desc: val });
         if (val == "" || val == "null") {
            setError({ ...error, desc: true });
         } else {
            setError({ ...error, desc: false });
         }
      }
   }

   function checkForm() {
      if (Object.values(error).some((v) => v == true) == true || Object.values(dataForm).some((v) => v == "") == true) {
         setDisableBtn(true)
      } else {
         setDisableBtn(false)
      }
   }

   useEffect(() => {
      checkForm()
   }, [error, dataForm])


   async function handleEdit() {
      try {
         setLoading(true)
         const hasil = await decryptToken(String(token?.current));
         const response = await apiEditDiscussionGeneral({ user: hasil, title: dataForm.title, desc: dataForm.desc }, id);
         if (response.success) {
            dispatch(setUpdateDiscussionGeneralDetail(!update))
            Toast.show({ type: 'small', text1: 'Berhasil mengubah data', })
            router.back();
         }
      } 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: "Edit Diskusi",
               headerTitleAlign: "center",
               headerRight: () => (
                  <ButtonSaveHeader
                     disable={disableBtn || loading ? true : false}
                     category="update"
                     onPress={() => { handleEdit() }}
                  />
               ),
            }}
         />
         <ScrollView showsVerticalScrollIndicator={false} style={[Styles.h100]}>
            <View style={[Styles.p15]}>
               <InputForm
                  label="Judul"
                  type="default"
                  placeholder="Judul"
                  required
                  error={error.title}
                  value={dataForm.title}
                  errorText="Judul tidak boleh kosong"
                  onChange={(val) => validationForm("title", val)}
               />
               <InputForm
                  label="Diskusi"
                  type="default"
                  placeholder="Hal yang didiskusikan"
                  required
                  error={error.desc}
                  value={dataForm.desc}
                  errorText="Diskusi tidak boleh kosong"
                  onChange={(val) => validationForm("desc", val)}
                  multiline
               />
            </View>
         </ScrollView>
      </SafeAreaView>
   );
}
