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


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

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

  useEffect(() => {
    if (inputRef.current) {
      flatpickr(inputRef.current, {
        dateFormat: "d-m-Y",
        allowInput: allowText, 
        defaultDate: value
          ? flatpickr.parseDate(value, "Y-m-d")
          : null,
        maxDate:maxDate,
        minDate:new Date(minDate?.split("T")[0]) ?? undefined,
        onChange: function (selectedDates, dateStr) {
          onChange(dateStr); 
        },
        ...rest
      });
    }
  }, [inputRef]);

  return (
    <div className={` position-relative ${className}`}>
      <input
        type="text"
        className="form-control form-control-sm " 
        placeholder={placeholder}
          defaultValue={
          value ? flatpickr.formatDate(flatpickr.parseDate(value, "Y-m-d"), "d-m-Y") : ""
        }
        ref={(el) => {
          inputRef.current = el;
          ref(el);
        }}
        readOnly={!allowText}
        autoComplete="off"
      />

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

export default DatePicker;
