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

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

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

    endDate.setHours(0, 0, 0, 0);

    const startDate = new Date(endDate); 
    startDate.setDate(endDate.getDate() - (DateDifference - 1));
    startDate.setHours(0, 0, 0, 0);

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

    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;
