import { useState, useRef, useEffect } from 'react';
import { ChevronLeft, ChevronRight, Calendar as CalendarIcon } from 'lucide-react';
import clsx from 'clsx';

interface DateRangePickerProps {
    startDate: string; // YYYY-MM-DD
    endDate: string;   // YYYY-MM-DD
    onChange: (startDate: string, endDate: string) => void;
    align?: 'horizontal' | 'vertical';
}

export function DateRangePicker({ startDate, endDate, onChange, align = 'horizontal' }: DateRangePickerProps) {
    const [isOpen, setIsOpen] = useState(false);
    const containerRef = useRef<HTMLDivElement>(null);

    // Internal state for delayed update
    const [localStart, setLocalStart] = useState(startDate);
    const [localEnd, setLocalEnd] = useState(endDate);

    // View states for the two calendars
    const [leftViewDate, setLeftViewDate] = useState(new Date());
    const [rightViewDate, setRightViewDate] = useState(new Date());

    // Sync props to internal state and init view dates on open
    useEffect(() => {
        if (isOpen) {
            setLocalStart(startDate);
            setLocalEnd(endDate);

            const sDate = startDate ? new Date(startDate) : new Date();
            const eDate = endDate ? new Date(endDate) : new Date();

            setLeftViewDate(new Date(sDate.getFullYear(), sDate.getMonth(), 1));
            setRightViewDate(new Date(eDate.getFullYear(), eDate.getMonth(), 1));
        }
    }, [isOpen, startDate, endDate]);

    // Close on click outside
    useEffect(() => {
        function handleClickOutside(event: MouseEvent) {
            if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        }
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    const formatDate = (date: Date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    };

    const setPreset = (type: 'today' | 'tomorrow' | 'thisWeek' | 'thisMonth' | 'lastMonth') => {
        const today = new Date();
        let newStart = today;
        let newEnd = today;

        switch (type) {
            case 'today':
                break;
            case 'tomorrow':
                const tomorrow = new Date(today);
                tomorrow.setDate(today.getDate() + 1);
                newStart = tomorrow;
                newEnd = tomorrow;
                break;
            case 'thisWeek':
                const day = today.getDay();
                const diff = today.getDate() - day; // Sunday start
                newStart = new Date(today.setDate(diff));
                newEnd = new Date(today.setDate(diff + 6));
                break;
            case 'thisMonth':
                newStart = new Date(today.getFullYear(), today.getMonth(), 1);
                newEnd = new Date(today.getFullYear(), today.getMonth() + 1, 0);
                break;
            case 'lastMonth':
                newStart = new Date(today.getFullYear(), today.getMonth() - 1, 1);
                newEnd = new Date(today.getFullYear(), today.getMonth(), 0);
                break;
        }

        const sStr = formatDate(newStart);
        const eStr = formatDate(newEnd);
        setLocalStart(sStr);
        setLocalEnd(eStr);

        // Update views to match selection
        setLeftViewDate(new Date(newStart.getFullYear(), newStart.getMonth(), 1));
        setRightViewDate(new Date(newEnd.getFullYear(), newEnd.getMonth(), 1));
    };

    const handleConfirm = () => {
        onChange(localStart, localEnd);
        setIsOpen(false);
    };

    const handleCancel = () => {
        setIsOpen(false);
    };

    const toggleOpen = () => setIsOpen(!isOpen);

    // --- Calendar Logic ---
    const getDaysInMonth = (year: number, month: number) => new Date(year, month + 1, 0).getDate();
    const getFirstDayOfMonth = (year: number, month: number) => new Date(year, month, 1).getDay();

    const renderCalendarGrid = (viewDate: Date, setViewDate: (d: Date) => void, type: 'start' | 'end') => {
        const year = viewDate.getFullYear();
        const month = viewDate.getMonth();
        const daysInMonth = getDaysInMonth(year, month);
        const firstDay = getFirstDayOfMonth(year, month);

        const days = [];
        for (let i = 0; i < firstDay; i++) {
            days.push(<div key={`empty-${i}`} className="h-8 w-8" />);
        }

        for (let day = 1; day <= daysInMonth; day++) {
            const current = new Date(year, month, day);
            const dateStr = formatDate(current);

            // Only highlight the date corresponding to the specific calendar type
            const isSelected = type === 'start'
                ? localStart === dateStr
                : localEnd === dateStr;

            days.push(
                <button
                    key={day}
                    onClick={() => handleDateClick(dateStr, type)}
                    className={clsx(
                        "h-8 w-8 rounded-full flex items-center justify-center text-xs transition-all relative",
                        // Selected
                        isSelected ? "bg-blue-600 text-white font-bold hover:bg-blue-500 z-10 ring-2 ring-blue-400/50" : "text-white/80 hover:bg-white/10"
                    )}
                >
                    {day}
                </button>
            );
        }

        return (
            <div className="w-[240px]">
                {/* Header */}
                <div className="flex items-center justify-between mb-2 px-2">
                    <button onClick={() => {
                        const d = new Date(viewDate);
                        d.setMonth(d.getMonth() - 1);
                        setViewDate(d);
                    }} className="p-1 hover:bg-white/10 rounded text-white/70">
                        <ChevronLeft className="w-4 h-4" />
                    </button>
                    <span className="text-sm font-semibold text-white">
                        {year}년 {month + 1}월
                    </span>
                    <button onClick={() => {
                        const d = new Date(viewDate);
                        d.setMonth(d.getMonth() + 1);
                        setViewDate(d);
                    }} className="p-1 hover:bg-white/10 rounded text-white/70">
                        <ChevronRight className="w-4 h-4" />
                    </button>
                </div>
                {/* Days Header */}
                <div className="grid grid-cols-7 gap-1 text-center mb-1">
                    {['일', '월', '화', '수', '목', '금', '토'].map(day => (
                        <div key={day} className="text-[10px] text-white/40 font-medium py-1">
                            {day}
                        </div>
                    ))}
                </div>
                {/* Days Grid */}
                <div className="grid grid-cols-7 gap-1">
                    {days}
                </div>
            </div>
        );
    };

    const handleDateClick = (dateStr: string, type: 'start' | 'end') => {
        if (type === 'start') {
            setLocalStart(dateStr);
            // Validation: Start cannot be after End
            if (localEnd && new Date(dateStr) > new Date(localEnd)) {
                setLocalEnd(dateStr);
            }
        } else {
            setLocalEnd(dateStr);
            // Validation: End cannot be before Start
            if (localStart && new Date(dateStr) < new Date(localStart)) {
                setLocalStart(dateStr);
            }
        }
    };

    return (
        <div className="relative inline-block" ref={containerRef}>
            {/* Trigger */}
            <div
                onClick={toggleOpen}
                className={clsx(
                    "bg-white/5 border border-white/10 rounded-lg px-3 py-2 cursor-pointer hover:bg-white/10 transition-colors w-fit",
                    align === 'vertical' ? 'flex flex-col items-start gap-1' : 'flex items-center gap-2'
                )}
            >
                {align === 'horizontal' ? (
                    <>
                        <CalendarIcon className="w-4 h-4 text-white/50" />
                        <span className="text-white text-sm font-medium">
                            {startDate} <span className="text-white/50 mx-1">~</span> {endDate}
                        </span>
                    </>
                ) : (
                    <>
                        <div className="flex items-center gap-2">
                            <span className="text-white/50 text-xs">시작</span>
                            <span className="text-white text-sm font-medium tracking-wider">{startDate}</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <span className="text-white/50 text-xs">종료</span>
                            <span className="text-white text-sm font-medium tracking-wider">{endDate}</span>
                        </div>
                    </>
                )}
            </div>

            {/* Popover */}
            {isOpen && (
                <div className="absolute top-full left-0 mt-2 z-[9999] bg-[#1e1e2e] border border-white/10 rounded-xl shadow-xl p-4 w-auto backdrop-blur-md">

                    {/* Presets Grid */}
                    <div className="flex flex-wrap gap-2 mb-4 justify-center">
                        <button onClick={() => setPreset('today')} className="px-3 py-1.5 bg-white/5 hover:bg-white/10 rounded-full text-xs text-white/80 border border-white/5 transition-colors">오늘</button>
                        <button onClick={() => setPreset('tomorrow')} className="px-3 py-1.5 bg-white/5 hover:bg-white/10 rounded-full text-xs text-white/80 border border-white/5 transition-colors">내일</button>
                        <button onClick={() => setPreset('thisWeek')} className="px-3 py-1.5 bg-white/5 hover:bg-white/10 rounded-full text-xs text-white/80 border border-white/5 transition-colors">이번주</button>
                        <button onClick={() => setPreset('thisMonth')} className="px-3 py-1.5 bg-white/5 hover:bg-white/10 rounded-full text-xs text-white/80 border border-white/5 transition-colors">이번달</button>
                        <button onClick={() => setPreset('lastMonth')} className="px-3 py-1.5 bg-white/5 hover:bg-white/10 rounded-full text-xs text-white/80 border border-white/5 transition-colors">저번달</button>
                    </div>

                    <div className="h-px bg-white/10 mb-4" />

                    {/* Dual Calendars Container */}
                    <div className="flex flex-col md:flex-row gap-6">
                        {renderCalendarGrid(leftViewDate, setLeftViewDate, 'start')}

                        {/* Mobile/Desktop separator or spacer */}
                        <div className="hidden md:block w-px bg-white/10 self-stretch my-2"></div>

                        {renderCalendarGrid(rightViewDate, setRightViewDate, 'end')}
                    </div>

                    <div className="h-px bg-white/10 my-4" />

                    {/* Action Buttons */}
                    <div className="flex justify-end gap-2">
                        <button
                            onClick={handleCancel}
                            className="px-4 py-2 rounded-lg text-sm text-white/70 hover:bg-white/10 transition-colors"
                        >
                            취소
                        </button>
                        <button
                            onClick={handleConfirm}
                            className="px-4 py-2 rounded-lg text-sm bg-blue-600 hover:bg-blue-500 text-white font-medium transition-colors"
                        >
                            확인
                        </button>
                    </div>
                </div>
            )}
        </div>
    );
}
