import React, { useEffect, useRef } from "react";

const DateRangePicker = ({
  onRangeChange,
  DateDifference = 7,
  endDateMode = "yesterday", // "today" or "yesterday"
}) => {
  const inputRef = useRef(null);

  useEffect(() => {
    const endDate = new Date();
    if (endDateMode === "yesterday") {
      endDate.setDate(endDate.getDate() - 1);
    }

    const startDate = new Date();
    startDate.setDate(endDate.getDate() - DateDifference);

    const fp = flatpickr(inputRef.current, {
      mode: "range",
      dateFormat: "Y-m-d",
      altInput: true,
      altFormat: "d-m-Y",
      defaultDate: [startDate, endDate],
      static: true,
      clickOpens: true,
      onChange: (selectedDates, dateStr) => {
        const [startDate, endDate] = dateStr.split(" to ");
        onRangeChange?.({ startDate, endDate });
      },
    });

    onRangeChange?.({
      startDate: startDate.toLocaleDateString("en-CA"),
      endDate: endDate.toLocaleDateString("en-CA"),
    });

    return () => {
      fp.destroy();
    };
  }, [onRangeChange, DateDifference, endDateMode]);

  return (
    <input
      type="text"
      className="form-control form-control-sm ms-1"
      placeholder="From to End"
      id="flatpickr-range"
      ref={inputRef}
    />
  );
};

export default DateRangePicker;