import { useState, useEffect, useRef } from "react";
import moment from "moment";
import Datepicker from "react-tailwindcss-datepicker";
const DatePickerControl = ({
  date = null,
  onChange = () => {},
  label = "Select a Date",
  variant = "button",
  adminSection = false,
}) => {
  const [open, setOpen] = useState(false);
  const wrapperRef = useRef(null);
  const [value, setValue] = useState({
    startDate: date ? moment(date).startOf("day").toDate() : null,
    endDate: null,
  });

  // useEffect(() => {
  //   const editor = document.querySelector(".block-editor__container");

  //   function handleClickOutside(event) {
  //     if (wrapperRef.current && !wrapperRef.current.contains(event.target)) {
  //       setOpen(false);
  //     }
  //   }
  //   editor.addEventListener("mousedown", handleClickOutside);
  //   return () => editor.removeEventListener("mousedown", handleClickOutside);
  // }, []);

  const minDate = moment().startOf("day").toDate();

  useEffect(() => {
    setValue({
      startDate: date ? moment(date).startOf("day").toDate() : null,
      endDate: null,
    });
  }, [date]);

  const handleDateChange = (val) => {
    setValue(val);

    if (val?.startDate) {
      const newDate = moment(val.startDate);
      onChange(newDate);
    } else {
      onChange(null);
    }
  };

  return (
    <Datepicker
      ref={wrapperRef}
      minDate={minDate}
      asSingle={true}
      useRange={false}
      displayFormat={"MMM DD, YYYY"}
      selected={value}
      value={value}
      placeholder={
        value?.startDate &&
        moment(value.startDate, moment.ISO_8601, true).isValid()
          ? moment(value.startDate).format("MMM DD, YYYY")
          : "Select dates"
      }
      inputClassName={`input-control section-description text-left w-full ${
        variant === "button"
          ? adminSection
            ? "max-w-full"
            : "max-w-[10rem]"
          : "w-full"
      } ${
        adminSection ? "min-w-[8rem]" : "min-w-[10rem]"
      } min-w-8 shadow-sm border-solid border border-gray-300 bg-white placeholder-gray-700 max-sm:w-full`}
      onChange={handleDateChange}
      show={open}
    />
  );
};
export default DatePickerControl;
