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

import "react-date-range/dist/styles.css"; // main css file
import "react-date-range/dist/theme/default.css"; // theme css file
import { DateRange } from "react-date-range";

export default function CustomDateRangePicker({ startDate, endDate, setStartRange, setEndRange }) {
    const minDate = new Date("2025-07-01")
    const maxDate = new Date()
    const [showCalendar, setShowCalendar] = useState(false);
    const calendarRef = useRef(null);

    // Create range object for react-date-range
    const range = [{
        startDate: startDate,
        endDate: endDate,
        key: 'selection'
    }];

    const handleSelect = (ranges) => {
        const { startDate: newStart, endDate: newEnd } = ranges.selection;
        
        setStartRange(newStart);
        setEndRange(newEnd);
        
        if (
            newStart &&
            newEnd &&
            newStart.getTime() !== newEnd.getTime()
        ) {
            setShowCalendar(false);
        }
    };

    // Hide calendar when clicking outside
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (
                calendarRef.current &&
                !calendarRef.current.contains(event.target)
            ) {
                setShowCalendar(false);
            }
        };

        if (showCalendar) {
            document.addEventListener("mousedown", handleClickOutside);
        } else {
            document.removeEventListener("mousedown", handleClickOutside);
        }

        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, [showCalendar]);

    return (
        <div ref={calendarRef} style={{ position: "relative" }}>
            <button onClick={() => setShowCalendar((prev) => !prev)}>
                {startDate?.toLocaleDateString()} -{" "}
                {endDate?.toLocaleDateString()}
            </button>

            {showCalendar && (
                <div style={{ position: "fixed", zIndex: 9999 }}>
                    <DateRange
                        minDate={minDate}
                        maxDate={maxDate}
                        ranges={range}
                        onChange={handleSelect}
                        moveRangeOnFirstSelection={false}
                    />
                </div>
            )}
        </div>
    );
}