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


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

  useEffect(() => {

    const today = new Date();
    const fifteenDaysAgo = new Date();
    fifteenDaysAgo.setDate(today.getDate() - 15);

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

    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;
