import { ObjectId } from 'bson';
import { FC, useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import { Button, Stack } from '../../components';
import { LeaveType, soriAPIClient } from '../../lib/sori';
import { CSelect } from '@/components/ui/c-select';

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

type FormValues = {
  leaveType: LeaveType;
  amount: number;
  remark: string;
};

export const CreateLeaveCreditApplicationForm: FC<
  CreateLeaveCreditApplicationProps
> = ({ onClose, open }) => {
  const { register, handleSubmit, reset, setValue } = useForm<FormValues>({
    defaultValues: {
      leaveType: 'annual',
      amount: 0,
      remark: '',
    },
  });
  useEffect(() => {
    if (!open) {
      reset({
        leaveType: 'annual',
        amount: 0,
        remark: '',
      });
    }
  }, [open]);

  const leaveTypes: LeaveType[] = Object.values(LeaveType.Enum);

  // const currentWorkDayType = watch('workDayType');
  // const currentDateRange = watch('dateRange');
  // const [halfDayWarning, setHalfDayWarning] = useState<string | null>(null);
  // const [weekendWarning, setWeekendWarning] = useState<string | null>(null);
  const [buttonDisabled, setbuttonDisabled] = useState<boolean>(false);

  // useEffect(() => {
  //   if (!currentDateRange.start || !currentDateRange.end) {
  //     setHalfDayWarning(null);
  //     setWeekendWarning(null);
  //     setbuttonDisabled(false);
  //   } else if (
  //     currentWorkDayType !== 'full' &&
  //     currentDateRange.start.getTime() !== currentDateRange.end.getTime()
  //   ) {
  //     console.log('currentWorkDayType', currentWorkDayType);
  //     console.log('currentDateRange', currentDateRange);
  //     setHalfDayWarning('*Half day can only be applied for a single day.');
  //     setbuttonDisabled(true);
  //   } else if (
  //     currentDateRange.start.getDay() === 0 ||
  //     currentDateRange.end.getDay() === 6
  //   ) {
  //     setbuttonDisabled(true);
  //     setWeekendWarning('No leave required for weekends');
  //   } else {
  //     setHalfDayWarning(null);
  //     setWeekendWarning(null);
  //     setbuttonDisabled(false);
  //   }
  // }, [currentWorkDayType, currentDateRange]);

  const onFormSubmit = async (data: FormValues) => {
    const payload = {
      leaveType: data.leaveType,
      amount: Number(data.amount),
      appliedBy: new ObjectId('68d50e6f73dd78e6f9d2e098'),
      applyRemarks: data.remark,
    };

    const [error] =
      await soriAPIClient.leaveCreditApplications.actions.createLeaveCreditApplication(
        payload,
      );
    if (error) {
      console.error(error);
      onClose();
      toast.error('Failed to create leave credit application');
    } else {
      toast.success('Leave credit application 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">
          <h1 className="text-xl">Create Leave Credit</h1>
          <div className="flex flex-col gap-4">
            <div className="flex flex-col gap-1">
              <label>Leave Type</label>
              <CSelect
                options={leaveTypes.map((leaveType) => ({
                  label: leaveType,
                  value: leaveType,
                }))}
                onSelect={(selected) => {
                  const value = selected?.map((opt) => opt.value) ?? [];
                  setValue('leaveType', value[0] as LeaveType);
                }}
              />
            </div>
            <div className="flex flex-col gap-1">
              <label>Amount</label>
              <input
                type="number"
                {...register('amount')}
                className="border border-zinc-300 rounded bg-white px-2 py-1"
              />
            </div>
            <div className="flex flex-col gap-1">
              <label>Remark</label>
              <textarea
                {...register('remark')}
                rows={3}
                className="border border-zinc-300 rounded px-2 py-1"
              />
            </div>
          </div>

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