import React, { useEffect } from "react";
import { Modal } from "@/components/common/modal";
import { CalendarDaysIcon } from "@heroicons/react/24/outline";
import { X } from "lucide-react";
import { useForm } from "react-hook-form";
import { toast } from "react-toastify";

interface AddLeaveModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (leaveData: any) => void;
}

export default function AddLeaveModal({ isOpen, onClose, onSave }: AddLeaveModalProps) {
  const { register, handleSubmit, watch, reset, setValue, formState: { errors } } = useForm({
    defaultValues: {
      fromDate: "",
      toDate: "",
      leaveType: "FULL_DAY",
      reason: "",
    }
  });

  const fromDate = watch("fromDate");
  const toDate = watch("toDate");

  useEffect(() => {
    if (fromDate && toDate && fromDate !== toDate) {
      setValue("leaveType", "FULL_DAY");
    }
  }, [fromDate, toDate, setValue]);

  useEffect(() => {
    if (isOpen) {
      reset({ fromDate: "", toDate: "", leaveType: "FULL_DAY", reason: "" });
    }
  }, [isOpen, reset]);

  const today = new Date().toISOString().split("T")[0];

  const onSubmit = (data: any) => {
    // Format dates to ISO datetime strings to satisfy backend validation
    const formattedData = {
      ...data,
      fromDate: data.fromDate ? new Date(`${data.fromDate}T00:00:00`).toISOString() : undefined,
      toDate: data.toDate ? new Date(`${data.toDate}T00:00:00`).toISOString() : undefined,
    };
    onSave(formattedData);
    onClose();
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} className="max-w-[700px] m-4">
      <div className="no-scrollbar relative w-full max-w-[700px] rounded-3xl bg-white p-4 lg:p-8">
        <div className="px-2 pr-14 mb-6 lg:mb-7">
          <h4 className="text-xl lg:text-2xl font-semibold text-brand-950">
            Add Leave
          </h4>
        </div>
        {/* Body */}
        <form onSubmit={handleSubmit(onSubmit)} className="px-2">
          <div className="grid grid-cols-1 gap-x-6 gap-y-5 lg:grid-cols-2">
            <div className="col-span-2 lg:col-span-1">
              <label className="mb-1.5 block text-sm font-medium text-gray-700">
                From Date<span className="text-red-500">*</span>
              </label>
              <div className="relative">
                <input
                  type="date"
                  min={today}
                  {...register("fromDate", { required: "From Date is required" })}
                  onClick={(e) => e.currentTarget.showPicker?.()}
                  className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none ${errors.fromDate ? "border-red-500" : "border-gray-300"}`}
                />
                {errors.fromDate && <p className="text-red-500 text-xs mt-1">{errors.fromDate.message as string}</p>}
                <CalendarDaysIcon
                  className="absolute right-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400 cursor-pointer"
                  onClick={(e) => {
                    const input = e.currentTarget.parentElement?.querySelector("input") as HTMLInputElement;
                    input?.showPicker?.();
                    input?.focus();
                  }}
                />
              </div>
            </div>
            <div className="col-span-2 lg:col-span-1">
              <label className="mb-1.5 block text-sm font-medium text-gray-700">
                To Date<span className="text-red-500">*</span>
              </label>
              <div className="relative">
                <input
                  type="date"
                  min={today}
                  {...register("toDate", { required: "To Date is required" })}
                  onClick={(e) => e.currentTarget.showPicker?.()}
                  className={`h-11 w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none ${errors.toDate ? "border-red-500" : "border-gray-300"}`}
                />
                {errors.toDate && <p className="text-red-500 text-xs mt-1">{errors.toDate.message as string}</p>}
                <CalendarDaysIcon
                  className="absolute right-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400 cursor-pointer"
                  onClick={(e) => {
                    const input = e.currentTarget.parentElement?.querySelector("input") as HTMLInputElement;
                    input?.showPicker?.();
                    input?.focus();
                  }}
                />
              </div>
            </div>
            <div className="col-span-2">
              <label className="mb-1.5 block text-sm font-medium text-gray-700">
                Leave Type<span className="text-red-500">*</span>
              </label>
              <select
                {...register("leaveType", { required: "Leave Type is required" })}
                className="h-11 w-full rounded-lg border appearance-none border-gray-300 px-4 py-2.5 text-sm shadow-theme-xs bg-transparent text-gray-800 outline-none disabled:bg-gray-100 disabled:text-gray-500"
                style={{
                  backgroundImage: `url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e")`,
                  backgroundPosition: "right 0.5rem center",
                  backgroundRepeat: "no-repeat",
                  backgroundSize: "1.5em 1.5em",
                }}
              >
                <option value="FULL_DAY">Full Day</option>
                <option value="HALF_DAY" disabled={fromDate !== "" && toDate !== "" && fromDate !== toDate}>Half Day</option>
              </select>
              {errors.leaveType && <p className="text-red-500 text-xs mt-1">{errors.leaveType.message as string}</p>}
            </div>

            <div className="col-span-2">
              <label className="mb-1.5 block text-sm font-medium text-gray-700">
                Reason<span className="text-red-500">*</span>
              </label>
              <textarea
                {...register("reason", { required: "Reason is required" })}
                rows={4}
                className={`w-full rounded-lg border appearance-none px-4 py-2.5 text-sm shadow-theme-xs placeholder:text-gray-400 bg-transparent text-gray-800 outline-none resize-y align-middle ${errors.reason ? "border-red-500" : "border-gray-300"}`}
              ></textarea>
              {errors.reason && <p className="text-red-500 text-xs mt-1">{errors.reason.message as string}</p>}
            </div>
          </div>

          {/* Footer */}
          <div className="flex items-center gap-3 mt-6 lg:justify-end">
            <button
              type="button"
              onClick={onClose}
              className="flex items-center justify-center gap-2 rounded-lg border border-gray-300 bg-[#f7f8fa] px-4 py-3 text-sm font-medium text-gray-700"
            >
              Close
            </button>
            <button
              type="submit"
              className="inline-flex items-center justify-center font-medium gap-2 rounded-lg transition px-4 py-3 text-sm bg-brand-950 text-white shadow-theme-xs hover:text-brand-950 hover:bg-yellow-500 disabled:bg-yellow-500 disabled:opacity-50"
            >
              Save changes
            </button>
          </div>
        </form>
      </div>
    </Modal>
  );
}
