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

const CompanyModal = (state) => {
  const { props } = usePage()
  const MODAL_TYPE = `company`
  const backButtonRef = useRef()

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

  const { data, setData, errors, processing } = useForm({
    company_id: props.company?.id ?? companyIdParam,
  });

  let companyIndex = null;
  if (props.companies.length > 0) {
    companyIndex = data.company_id ? props.companies.findIndex((option) => option.value == data.company_id) : null
  }

  const handleChangeCompany = (e) => {
    setData((state) => ({
      ...state,
      company_id: e?.value,
    }))
  }

  const handleSubmit = (e) => {
    e.preventDefault()
    setCookie('company_id', data.company_id, 365, {
      onSuccess: () => {
        if (!data.company_id) {
          deleteCookie('department_id', {
            onSuccess: () => {
              backButtonRef.current?.click()
              router.visit('/admin/dashboard')
            }
          })
        } else {
          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 Perusahaan Aktif</h1>
        <p>Semua aktivitas selama sesi ini akan terkait dengan perusahaan yang dipilih.</p>

        <div className="mt-4">
          <Select
            isReactSelect={true}
            isVirtualized={true}
            isLabel={false}
            name='company_id'
            handleChange={handleChangeCompany}
            data={data}
            errors={errors}
            defaultValue={props.companies[companyIndex]}
            options={props.companies}
          />
        </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 CompanyModal
