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

const DateRangePicker = ({
  md,
  sm,
  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: false,       
      appendTo: document.body,
      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 (
<div className={`col-${sm} col-sm-${md} px-1 position-relative`}>
  <input
    type="text"
    className="form-control form-control-sm ps-2 pe-5  "
    placeholder="From to End"
    id="flatpickr-range"
    ref={inputRef}
  />

  <i
    className="bx bx-calendar calendar-icon cursor-pointer"
    style={{
      position: "absolute",
      top: "50%",
      right: "12px",
      transform: "translateY(-50%)",
      color: "#6c757d",
      fontSize: "1.1rem",
     
    }}
  ></i>
</div>

  );
};

export default DateRangePicker;
