import Styles from "@/constants/Styles"
import { apiCreatePosition } from "@/lib/api"
import { setUpdatePosition } from "@/lib/positionSlice"
import { useAuthSession } from "@/providers/AuthProvider"
import { AntDesign } from "@expo/vector-icons"
import { 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 ButtonMenuHeader from "../buttonMenuHeader"
import DrawerBottom from "../drawerBottom"
import { InputForm } from "../inputForm"
import MenuItemRow from "../menuItemRow"
import ModalFilter from "../modalFilter"
import ModalSelect from "../modalSelect"
import SelectForm from "../selectForm"

export default function HeaderRightPositionList() {
   const dispatch = useDispatch()
   const update = useSelector((state: any) => state.positionUpdate)
   const { token, decryptToken } = useAuthSession()
   const entityUser = useSelector((state: any) => state.user)
   const [isVisible, setVisible] = useState(false)
   const [isVisibleTambah, setVisibleTambah] = useState(false)
   const [isFilter, setFilter] = useState(false)
   const [isSelect, setSelect] = useState(false)
   const [choose, setChoose] = useState({ val: '', label: '' })
   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 = true
      if (dataForm.name == "") {
         setError(error => ({ ...error, name: true }))
         nilai = false
      }

      if ((entityUser.role == "supadmin" || entityUser.role == "developer") && (dataForm.idGroup == "" || String(dataForm.idGroup) == "null")) {
         setError(error => ({ ...error, idGroup: true }))
         nilai = false
      }

      return nilai
   }

   function onCheck() {
      const check = checkAll()
      if (!check)
         return false
      handleTambah()
   }


   async function handleTambah() {
      try {
         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 {
         setVisibleTambah(false)
         setVisible(false)
         Toast.show({ type: 'small', text1: 'Berhasil menambahkan data', })
      }

   }


   return (
      <>
         {entityUser.role != 'user' ? <ButtonMenuHeader onPress={() => { setVisible(true) }} /> : <></>}
         <DrawerBottom animation="slide" isVisible={isVisible} setVisible={setVisible} title="Menu">
            <View style={Styles.rowItemsCenter}>
               <MenuItemRow
                  icon={<AntDesign name="pluscircle" color="black" size={25} />}
                  title="Tambah Jabatan"
                  onPress={() => {
                     setVisible(false)
                     setVisibleTambah(true)
                  }}
               />
               {
                  (entityUser.role == 'supadmin' || entityUser.role == 'developer') &&
                  <MenuItemRow
                     icon={<AntDesign name="filter" color="black" size={25} />}
                     title="Filter"
                     onPress={() => {
                        setVisible(false)
                        setFilter(true)
                     }}
                  />
               }
            </View>
         </DrawerBottom>

         <DrawerBottom animation="slide" height={45} isVisible={isVisibleTambah} setVisible={setVisibleTambah} title="Tambah Jabatan">
            <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={() => {
                           setVisibleTambah(false)
                           setSelect(true)
                        }}
                        error={error.idGroup}
                        errorText="Lembaga Desa harus diisi"
                     />
                  }
                  <InputForm
                     type="default"
                     placeholder="Nama Jabatan"
                     required
                     label="Jabatan"
                     onChange={(value) => { validationForm(value, 'name') }}
                     error={error.name}
                     errorText="Nama jabatan harus diisi"
                     value={dataForm.name}
                  />
               </View>
               <View style={Styles.mb30}>
                  <ButtonForm text="SIMPAN" onPress={() => { onCheck() }} />
               </View>
            </View>
         </DrawerBottom>

         <ModalFilter close={() => {
            setFilter(false)
            setVisible(false)
         }} open={isFilter} page="position" />

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