import { useEffect, useRef } from "react";
import { useController } from "react-hook-form";

const DatePicker = ({
  name,
  control,
  placeholder = "DD-MM-YYYY",
  className = "",
  allowText = false,
  maxDate,
  minDate,
  disabled = false,
  ...rest
}) => {
  const inputRef = useRef(null);

  const {
    field: { onChange, value, ref }
  } = useController({
    name,
    control
  });

  useEffect(() => {
    if (!inputRef.current) return;

    const fp = flatpickr(inputRef.current, {
      dateFormat: "d-m-Y",
      allowInput: allowText,
      defaultDate: value ? new Date(value) : null, // safely convert to Date
      maxDate: maxDate ? new Date(maxDate) : undefined,
      minDate: minDate ? new Date(minDate) : undefined,
      onChange: (selectedDates) => {
        if (selectedDates.length > 0) {
          onChange(flatpickr.formatDate(selectedDates[0], "Y-m-d"));
        } else {
          onChange("");
        }
      },
      ...rest
    });

    return () => {
      fp.destroy(); // clean up on unmount
    };
  }, [inputRef, value, allowText, maxDate, minDate, rest, onChange]);

  const displayValue = value ? flatpickr.formatDate(new Date(value), "d-m-Y") : "";

  return (
    <div className={`position-relative ${className} w-max `}>
      <input
        type="text"
        className="form-control form-control form-control-sm"
        placeholder={placeholder}
        value={displayValue}
        onChange={(e) => {
          if (allowText) {
            onChange(e.target.value); // allow manual typing if enabled
          }
        }}
        ref={(el) => {
          inputRef.current = el;
          ref(el);
        }}
        readOnly={!allowText}
        autoComplete="off"
        disabled={disabled}
      />

      <span
        className="position-absolute top-50 end-0 pe-1 translate-middle-y cursor-pointer"
        onClick={() => {
          if (inputRef.current?._flatpickr) {
            inputRef.current._flatpickr.open();
          }
        }}
      >
        <i className="bx bx-calendar bx-sm fs-5 text-muted"></i>
      </span>
    </div>
  );
};

export default DatePicker;
