import Select from '@/Components/Form/Select'
import WithModal from '@/Components/WithModal'
import { setCookie } from '@/utils/format'
import { router, useForm, usePage } from '@inertiajs/react'
import { useRef } from 'react'

const DepartmentModal = (state) => {
  const { props } = usePage()
  const MODAL_TYPE = `department`
  const backButtonRef = useRef()

  const params = new URLSearchParams((new URL(props.location)).search);
  let departmentIdParam = params.get("department_id");

  const { data, setData, errors, processing } = useForm({
    department_id: props.department?.id ?? departmentIdParam,
  });

  let departmentIndex = null;
  if (props.departments.length > 0) {
    departmentIndex = data.department_id ? props.departments.findIndex((option) => option.value == data.department_id) : null
  }

  const handleChangeDepartment = (e) => {
    setData((state) => ({
      ...state,
      department_id: e?.value,
    }))
  }

  const handleSubmit = (e) => {
    e.preventDefault()
    setCookie('department_id', data.department_id, 365, {
      onSuccess: () => {
        backButtonRef.current?.click()
        router.visit('/admin/dashboard')
      }
    })
  }

  return (
    <WithModal type={MODAL_TYPE} modalBoxSize="max-w-2xl">
      <form action=''>
        <h1 className='text-lg font-bold'>Pilih Departemen Aktif</h1>
        <p>Semua aktivitas selama sesi ini akan terkait dengan departemen yang dipilih.</p>

        <div className="mt-4">
          <Select
            isReactSelect={true}
            isVirtualized={true}
            isLabel={false}
            name='department_id'
            handleChange={handleChangeDepartment}
            data={data}
            errors={errors}
            defaultValue={props.departments[departmentIndex]}
            options={props.departments}
          />
        </div>

        <div className='modal-action'>
          <label ref={backButtonRef} htmlFor={`modal_${MODAL_TYPE}`} className='btn btn-sm btn-neutral btn-outline'>
            Kembali
          </label>
          <button onClick={handleSubmit} className={`btn btn-sm btn-primary text-white `} disabled={processing}>
            <span className={`${processing && 'loading'}`}>Simpan</span>
          </button>
        </div>
      </form>
    </WithModal>
  )
}

export default DepartmentModal
