import { FC, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { Button, Stack } from '../../components';
import { Role, soriAPIClient } from '../../lib/sori';

type CreateFleetProps = {
  onClose: () => void;
  open: boolean;
};

type FormValues = {
  nameEn: string;
  nameZh: string;
  role: Role;
  hkId: string;
};

export const CreateStaffForm: FC<CreateFleetProps> = ({ onClose, open }) => {
  const { register, handleSubmit, reset } = useForm<FormValues>({
    defaultValues: {
      nameEn: '',
      nameZh: '',
      role: 'manager',
      hkId: '',
    },
  });
  useEffect(() => {
    if (!open) {
      reset();
    }
  }, [open]);

  const onFormSubmit = async (data: FormValues) => {
    const payload = {
      nameEN: data.nameEn,
      nameZH: data.nameZh,
      role: data.role,
      hkId: data.hkId,
      preferences: { attendanceReminderEnabled: true },
    };

    const [error] = await soriAPIClient.staffs.actions.createStaff(payload);
    if (error) {
      console.error(error);
      onClose();
      toast.error('Failed to create staff');
    } else {
      toast.success('Staff created successfully');
      onClose();
    }
  };

  return (
    <div>
      <form onSubmit={handleSubmit(onFormSubmit)}>
        <Stack className="w-100vw flex flex-col gap-4 border-gray-200 rounded-lg bg-white p-6 text-black sm:max-w-130 dark:bg-zinc-800 dark:text-white/90">
          <div className="flex flex-col gap-4">
            <h1>Create Staff</h1>
            <div className="flex flex-col gap-1">
              <label>Name (EN)</label>
              <input
                {...register('nameEn')}
                className="border border-zinc-300 rounded bg-white px-2 py-1"
              />
            </div>

            <div className="flex flex-col gap-1">
              <label>Name (ZH)</label>
              <input
                {...register('nameZh')}
                className="border border-zinc-300 rounded bg-white px-2 py-1"
              />
            </div>

            <div className="flex flex-col gap-1">
              <label>Role</label>
              <input
                {...register('role')}
                className="border border-zinc-300 rounded bg-white px-2 py-1"
              />
            </div>

            <div className="flex flex-col gap-1">
              <label>HK Id</label>
              <input
                {...register('hkId')}
                className="border border-zinc-300 rounded bg-white px-2 py-1"
              />
            </div>
          </div>

          <Button className="mt-auto bg-blue-5 text-white" type="submit">
            Save
          </Button>
        </Stack>
      </form>
    </div>
  );
};
