import Styles from "@/constants/Styles"
import { apiCreatePosition } from "@/lib/api"
import { setUpdatePosition } from "@/lib/positionSlice"
import { useAuthSession } from "@/providers/AuthProvider"
import { useTheme } from "@/providers/ThemeProvider"
import { update } from "@react-native-firebase/database"
import { useEffect, useState } from "react"
import { View } from "react-native"
import Toast from "react-native-toast-message"
import { useDispatch, useSelector } from "react-redux"
import { ButtonForm } from "../buttonForm"
import { InputForm } from "../inputForm"
import ModalSelect from "../modalSelect"
import SelectForm from "../selectForm"

export default function ModalFormCreatePosition({ onClose }: { onClose: () => void }) {
   const dispatch = useDispatch()
   const { token, decryptToken } = useAuthSession()
   const entityUser = useSelector((state: any) => state.user)
   const { colors } = useTheme()
   const [choose, setChoose] = useState({ val: '', label: '' })
   const [isSelect, setSelect] = useState(false)
   const [disable, setDisable] = useState(true)
   const [dataForm, setDataForm] = useState({
      name: "",
      idGroup: "",
   })
   const [error, setError] = useState({
      name: false,
      idGroup: false
   });

   function validationForm(val: any, cat: 'name' | 'idGroup') {
      if (cat === 'name') {
         setDataForm({ ...dataForm, name: val })
         if (val == "") {
            setError({ ...error, name: true })
         } else {
            setError({ ...error, name: false })
         }
      } else if (cat === "idGroup") {
         setDataForm({ ...dataForm, idGroup: val })
         if (val == "") {
            setError({ ...error, idGroup: true })
         } else {
            setError({ ...error, idGroup: false })
         }
      }
   }

   function checkAll() {
      let nilai = false
      if (dataForm.name == "") {
         nilai = true
      }

      if ((entityUser.role == "supadmin" || entityUser.role == "developer") && (dataForm.idGroup == "" || String(dataForm.idGroup) == "null")) {
         nilai = true
      }

      setDisable(nilai)
   }

   useEffect(() => {
      checkAll()
   }, [dataForm])

   async function handleTambah() {
      try {
         setDisable(true)
         const hasil = await decryptToken(String(token?.current))
         const response = await apiCreatePosition({ user: hasil, name: dataForm.name, idGroup: dataForm.idGroup })
         dispatch(setUpdatePosition(!update))
      } catch (error) {
         console.error(error)
      } finally {
         setDisable(false)
         Toast.show({ type: 'small', text1: 'Berhasil menambahkan data', })
         onClose()
      }

   }

   return (
      <>
         <View style={{ flex: 1, justifyContent: 'space-between' }}>
            <View>
               {
                  (entityUser.role == 'supadmin' || entityUser.role == 'developer') &&
                  <SelectForm
                     label="Lembaga Desa"
                     placeholder="Pilih Lembaga Desa"
                     value={choose.label}
                     required
                     onPress={() => {
                        setSelect(true)
                     }}
                     error={error.idGroup}
                     errorText="Lembaga Desa harus diisi"
                     bg="transparent"
                  />
               }
               <InputForm
                  type="default"
                  placeholder="Nama Jabatan"
                  required
                  label="Jabatan"
                  onChange={(value) => { validationForm(value, 'name') }}
                  error={error.name}
                  bg={"transparent"}
                  errorText="Nama jabatan harus diisi"
                  value={dataForm.name}
               />
            </View>
            <View style={Styles.mb30}>
               <ButtonForm
                  text="SIMPAN"
                  onPress={() => { handleTambah() }}
                  disabled={disable} />
            </View>
         </View>

         <ModalSelect
            category="group"
            close={setSelect}
            onSelect={(value) => {
               validationForm(value.val, 'idGroup')
               setChoose(value)
               setSelect(false)
            }}
            title="Lembaga Desa"
            open={isSelect}
            valChoose={choose.val}
         />
      </>
   )
}