import { useEffect } from "react";
import { Link, useForm, usePage } from "@inertiajs/react";
import Input from "./Form/Input";
import Select from "./Form/Select";
import { useState } from "react";
import useLang from "@/utils/useLang";
import { useStatusLabel } from "@/utils/useStatus";
import { getBasePageUrl, mimeType, useSearchParams } from "@/utils/format";
import useFormChange, { handleSelectReload } from "@/utils/useFormChange";

function RegisterForm({ userData = null }) {
  const { props } = usePage();
  const { location, status = null, roles = null, owners = null, companies, page } = usePage().props;
  const user = props?.auth?.user;
  const role = user ? user.role : "guest";
  const [picture, setPicture] = useState(userData?.picture ?? null)

  const { data, setData, post, processing, errors, reset } = useForm({
    location: location,
    name: userData?.name ?? "",
    username: userData?.username ?? "",
    phone: userData?.phone ?? "",
    email: userData?.email ?? "",
    role: userData?.role ?? "",
    status: userData?.status ?? "active",
    picture: picture ?? "",
    password: "",
    password_confirmation: "",
    manager_id: userData?.manager_id ?? "",
    company_id: userData?.company_id ?? "",
  });

  useEffect(() => {
    if (location) {
      const params = new URLSearchParams(new URL(location).search);

      if (params.get("role")) {
        setData((state) => ({
          ...state,
          ["role"]: params.get("role"),
        }));
      }
    }
    return () => {
      reset("password", "password_confirmation");
    };
  }, []);

  function handleChange(e) {
    let { name, value, files } = useFormChange(e, data)

    if (['picture'].includes(name)) {
      setPicture(URL.createObjectURL(files[0]))
    }

    setData((state) => ({
      ...state,
      [name]: value
    }))
  }

  const submit = (e) => {
    e.preventDefault();

    if (userData) {
      data._method = "put";
      return post(`/admin/users/${userData.id}`);
    }

    post("/admin/users")
  };

  const inputProps = { handleChange, data, errors }

  const { params } = useSearchParams(location)
  let backUrl = props?.ref ?? params.get('ref')
  if (!backUrl) {
    backUrl = getBasePageUrl(page?.url)
  }

  let ownerIndex = null;
  if (owners?.length > 0) {
    ownerIndex = data?.['manager_id'] ? owners?.findIndex((option) => option.value == data?.['manager_id']) : null
  }

  return (
    <form onSubmit={submit} className="flex flex-col items-center justify-center w-full gap-4 p-4 border rounded-lg shadow-lg">
      <p className="text-lg font-semibold">{!!userData ? `Edit Pengguna` : `Tambah Pengguna`}</p>
      <div className="flex flex-col md:flex-row w-full gap-4">
        <Input type='text' name='name' label='nama' {...inputProps} />
        {userData ? (
          <Input type='text' name='username' label='username' {...inputProps} />
        ) : null}
        <Input type='email' name='email' label='email' {...inputProps} />
      </div>

      <div className="flex flex-col md:flex-row w-full gap-4">
        <Input type='tel' name='phone' label='nomor whatsapp' alt="Opsional" {...inputProps} />
        <Input type='password' name='password' label='password' {...inputProps} />
        <Input type='password' name='password_confirmation' label='Konfirmasi Password' {...inputProps} />
      </div>
      <div className="flex flex-col md:flex-row w-full gap-4">
        <div className="flex gap-2 items-end w-full">
          <Input type='file' name='picture' label='Upload Foto' alt='Opsional' {...inputProps} accept={mimeType('image')} />
          {picture ? (
            <img src={picture} alt="Foto Profil" className="w-16 h-16 object-cover rounded-full" />
          ) : null}
        </div>
        {['director', 'manager'].includes(role) && status ? (
          <>
            <Select name='status' label='status' {...inputProps} defaultValue={data.status}>
              <option value=''>Pilih salah satu</option>
              {status.length == 0 ? null : status.map((status, index) => (
                <option key={index} value={status} className='capitalize'>
                  {useStatusLabel(status)}
                </option>
              ))}
            </Select>
          </>
        ) : null}
        {['director'].includes(role) && status ? (
          <>
            <Select name='role' label='role' {...inputProps} defaultValue={data.role} handleChange={(e) => handleSelectReload({ e, name: 'role', data, setData, params, only: ['owners', 'companies'], isHtmlSelect: true })}>
              <option value=''>Pilih salah satu</option>
              {roles.length == 0 ? null : roles.map((role, index) => (
                <option key={index} value={role} className='capitalize'>
                  {useLang(role)}
                </option>
              ))}
            </Select>
          </>
        ) : null}
      </div>

      <div className="flex flex-col md:flex-row w-full gap-4">
        {['director'].includes(role) && ['user'].includes(data.role) && !!owners ? (
          <>
            <Select
              {...inputProps}
              isReactSelect={true}
              isVirtualized={true}
              name={'manager_id'}
              label={'Pilih Manajer'}
              options={owners}
              defaultValue={owners[ownerIndex]}
              handleChange={(e) => handleSelectReload({ e, name: 'manager_id', data, setData, params, only: ['companies'] })}
            />
          </>
        ) : null}
        {['', 'user', 'manager'].includes(data.role) ? (
          <Select
            {...inputProps}
            isReactSelect={true}
            name={'company_id'}
            label={'Pilih Perusahaan'}
            defaultValue={data.company_id}
            options={companies}
            isMulti={true}
            handleChange={(e) => setData('company_id', e)}
          />
        ) : null}

      </div>

      <div className="flex flex-col gap-4 my-4">
        <div className="flex flex-col">
          <div className="flex justify-center gap-2 mt-4">
            <Link type="button" href={backUrl} className="btn btn-primary btn-outline btn-sm">
              Batal
            </Link>
            <button className="btn btn-sm btn-primary" disabled={processing}>
              Simpan
            </button>
          </div>
        </div>
      </div>
    </form>
  );
}

export default RegisterForm;
