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

const DateRangePicker = ({ onRangeChange, DateDifference = 15 }) => {
  const inputRef = useRef(null);

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

    const fp = flatpickr(inputRef.current, {
      mode: "range",
      dateFormat: "Y-m-d",
      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;
