import ModalConfirmation from "@/components/ModalConfirmation";
import AppHeader from "@/components/AppHeader";
import ButtonNextHeader from "@/components/buttonNextHeader";
import { InputForm } from "@/components/inputForm";
import ModalSelect from "@/components/modalSelect";
import SelectForm from "@/components/selectForm";
import Styles from "@/constants/Styles";
import { apiCheckDivisionName } from "@/lib/api";
import { setFormCreateDivision } from "@/lib/divisionCreate";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import { router, Stack } 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 CreateDivision() {
   const { colors } = useTheme();
   const { token, decryptToken } = useAuthSession()
   const [isSelect, setSelect] = useState(false)
   const [chooseGroup, setChooseGroup] = useState({ val: "", label: "" })
   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.divisionCreate)
   const entityUser = useSelector((state: any) => state.user)
   const userLogin = useSelector((state: any) => state.entities)
   const [loadingBtn, setLoadingBtn] = useState(false)
   const [showWarningModal, setShowWarningModal] = useState(false)
   const [error, setError] = useState({
      idGroup: false,
      name: false,
   });
   const [dataForm, setDataForm] = useState({
      idGroup: "",
      name: "",
      desc: "",
   });

   function validationForm(cat: string, val: any, label?: string) {
      if (cat == "group") {
         setChooseGroup({ val, label: String(label) });
         dispatch(setFormCreateDivision({ ...update, member: [], admin: [] }));
         setDataForm({ ...dataForm, idGroup: val });
         if (val == "" || val == "null") {
            setError((error) => ({ ...error, group: true }));
         } else {
            setError((error) => ({ ...error, group: false }));
         }
      } else if (cat == "name") {
         setDataForm({ ...dataForm, name: val });
         if (val == "" || val == "null") {
            setError((error) => ({ ...error, name: true }));
         } else {
            setError((error) => ({ ...error, name: false }));
         }
      } else if (cat == "desc") {
         setDataForm({ ...dataForm, desc: val });
         if (val == "" || val == "null") {
            setError((error) => ({ ...error, desc: true }));
         } else {
            setError((error) => ({ ...error, desc: false }));
         }
      }
   }

   async function handleCheckName() {
      try {
         setLoadingBtn(true)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiCheckDivisionName({ data: { ...dataForm }, user: hasil })
         if (response.success) {
            if (!response.available) {
               setShowWarningModal(true)
            } else {
               handleSetData()
            }
         } else {
            Toast.show({ type: 'small', text1: response.message, })
         }
      } catch (error) {
         console.error(error)
         Toast.show({ type: 'small', text1: 'Terjadi kesalahan', })
      } finally {
         setLoadingBtn(false)
      }
   }

   async function handleSetData() {
      dispatch(setFormCreateDivision({ ...update, data: dataForm }))
      router.push(`./create/add-member`)
   }

   useEffect(() => {
      if (entityUser.role != "supadmin" && entityUser.role != "developer") {
         validationForm('group', userLogin.idGroup, userLogin.group);
      }
   }, []);

   return (
      <SafeAreaView style={{ flex: 1, backgroundColor: colors.background }}>
         <Stack.Screen
            options={{
               // headerLeft: () => (
               //    <ButtonBackHeader
               //       onPress={() => {
               //          router.back();
               //       }}
               //    />
               // ),
               headerTitle: "Tambah Divisi",
               headerTitleAlign: "center",
               // headerRight: () => (
               //    <ButtonNextHeader
               //       onPress={() => { handleCheckName() }}
               //       disable={loadingBtn || error.idGroup || error.name || chooseGroup.val == "" || chooseGroup.val == "null" || dataForm.name == "" || dataForm.name == "null"}
               //    />
               // ),
               header: () => (
                  <AppHeader title="Tambah Divisi"
                     showBack={true}
                     onPressLeft={() => router.back()}
                     right={<ButtonNextHeader
                        onPress={() => { handleCheckName() }}
                        disable={loadingBtn || error.idGroup || error.name || chooseGroup.val == "" || chooseGroup.val == "null" || dataForm.name == "" || dataForm.name == "null"}
                     />}
                  />
               )
            }}
         />
         <ScrollView
            showsVerticalScrollIndicator={false}
            style={[Styles.h100, { backgroundColor: colors.background }]}
         >
            <View style={[Styles.p15]}>
               {
                  (entityUser.role == "supadmin" || entityUser.role == "developer") &&
                  (
                     <SelectForm
                        label="Lembaga Desa"
                        placeholder="Pilih Lembaga Desa"
                        value={chooseGroup.label}
                        required
                        onPress={() => { setSelect(true) }}
                        error={error.idGroup}
                        errorText="Lembaga Desa tidak boleh kosong"
                     />
                  )
               }
               <InputForm
                  label="Nama Divisi"
                  type="default"
                  placeholder="Nama Divisi"
                  required
                  value={dataForm.name}
                  onChange={(val) => validationForm('name', val)}
                  error={error.name}
                  errorText="Nama divisi tidak boleh kosong"
               />
               <InputForm
                  label="Deskripsi"
                  type="default"
                  placeholder="Deskripsi Divisi"
                  value={dataForm.desc}
                  onChange={(val) => setDataForm({ ...dataForm, desc: val })}
                  multiline
               />
            </View>
         </ScrollView>

         <ModalSelect
            category={"group"}
            close={setSelect}
            onSelect={(value) => {
               validationForm('group', value.val, value.label);
            }}
            title="Lembaga Desa"
            open={isSelect}
            valChoose={chooseGroup.val}
         />

         <ModalConfirmation
            visible={showWarningModal}
            title="Peringatan"
            message="Nama divisi sudah ada. Tidak dapat membuat divisi dengan nama yang sama"
            onConfirm={() => setShowWarningModal(false)}
            onCancel={() => setShowWarningModal(false)}
            confirmText="Oke"
         />
      </SafeAreaView>
   );
}
