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

const DateRangePicker = ({ onRangeChange, DateDifference = 7, defaultStartDate = new Date() - 1 }) => {
  const inputRef = useRef(null);

  useEffect(() => {
    const today = new Date();;
    today.setDate(today.getDate() - 1);
    const fifteenDaysAgo = new Date();
   
    fifteenDaysAgo.setDate(today.getDate() - DateDifference);

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

    onRangeChange?.({
      // startDate: fifteenDaysAgo.toISOString().split("T")[0],
      // endDate: today.toISOString().split("T")[0],
      startDate: fifteenDaysAgo.toLocaleDateString("en-CA"),
      endDate: today.toLocaleDateString("en-CA"),
    });

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

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

export default DateRangePicker;
