import { useState, useEffect, useRef } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Clock, MapPin, Users, ChevronLeft, ChevronRight, ChevronDown } from 'lucide-react';
import { schedules } from '../../data/dummy';

function Schedule() {
    const [currentDate, setCurrentDate] = useState(new Date());
    const [selectedDate, setSelectedDate] = useState(null);
    const [showYearMonthPicker, setShowYearMonthPicker] = useState(false);
    const [viewMode, setViewMode] = useState('yearMonth'); // 'yearMonth' | 'months'
    const [slideDirection, setSlideDirection] = useState(0); // -1: prev, 1: next
    const pickerRef = useRef(null);

    // 외부 클릭시 팝업 닫기
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (pickerRef.current && !pickerRef.current.contains(event.target)) {
                setShowYearMonthPicker(false);
                setViewMode('yearMonth');
            }
        };

        if (showYearMonthPicker) {
            document.addEventListener('mousedown', handleClickOutside);
        }

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

    // 달력 관련 함수
    const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();
    const getFirstDayOfMonth = (year, month) => new Date(year, month, 1).getDay();

    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();
    const daysInMonth = getDaysInMonth(year, month);
    const firstDay = getFirstDayOfMonth(year, month);

    const days = ['일', '월', '화', '수', '목', '금', '토'];

    // 스케줄이 있는 날짜 목록
    const scheduleDates = schedules.map(s => s.date);

    const hasSchedule = (day) => {
        const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
        return scheduleDates.includes(dateStr);
    };

    const prevMonth = () => {
        setSlideDirection(-1);
        setCurrentDate(new Date(year, month - 1, 1));
    };

    const nextMonth = () => {
        setSlideDirection(1);
        setCurrentDate(new Date(year, month + 1, 1));
    };

    const selectDate = (day) => {
        const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
        setSelectedDate(selectedDate === dateStr ? null : dateStr);
    };

    // 년도 선택 시 월 선택 모드로 전환
    const selectYear = (newYear) => {
        setCurrentDate(new Date(newYear, month, 1));
        setViewMode('months');
    };

    // 월 선택 시 적용 후 닫기
    const selectMonth = (newMonth) => {
        setCurrentDate(new Date(year, newMonth, 1));
        setShowYearMonthPicker(false);
        setViewMode('yearMonth');
    };

    // 필터링된 스케줄
    const filteredSchedules = selectedDate
        ? schedules.filter(s => s.date === selectedDate)
        : schedules;

    const formatDate = (dateStr) => {
        const date = new Date(dateStr);
        const dayNames = ['일', '월', '화', '수', '목', '금', '토'];
        return {
            month: date.getMonth() + 1,
            day: date.getDate(),
            weekday: dayNames[date.getDay()],
        };
    };

    // 년도 범위 (현재 년도 기준 10년 단위)
    const startYear = Math.floor(year / 10) * 10 - 1;
    const yearRange = Array.from({ length: 12 }, (_, i) => startYear + i);
    
    // 현재 년도/월 확인 함수
    const isCurrentYear = (y) => new Date().getFullYear() === y;
    const isCurrentMonth = (m) => {
        const today = new Date();
        return today.getFullYear() === year && today.getMonth() === m;
    };
    
    // 월 배열
    const monthNames = ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'];
    
    // 년도 범위 이동
    const prevYearRange = () => setCurrentDate(new Date(year - 10, month, 1));
    const nextYearRange = () => setCurrentDate(new Date(year + 10, month, 1));

    return (
        <div className="py-16">
            <div className="max-w-7xl mx-auto px-6">
                {/* 헤더 */}
                <div className="text-center mb-12">
                    <motion.h1
                        initial={{ opacity: 0, y: -20 }}
                        animate={{ opacity: 1, y: 0 }}
                        className="text-4xl font-bold mb-4"
                    >
                        일정
                    </motion.h1>
                    <motion.p
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        transition={{ delay: 0.2 }}
                        className="text-gray-500"
                    >
                        프로미스나인의 다가오는 일정을 확인하세요
                    </motion.p>
                </div>

                <div className="flex gap-8">
                    {/* 달력 - 더 큰 사이즈 */}
                    <motion.div
                        initial={{ opacity: 0, x: -20 }}
                        animate={{ opacity: 1, x: 0 }}
                        className="w-[400px] flex-shrink-0"
                    >
                        <div className="bg-white rounded-2xl shadow-sm pt-8 px-8 pb-6 relative transition-all duration-200" ref={pickerRef}>
                            {/* 달력 헤더 */}
                            <div className="flex items-center justify-between mb-8">
                                <button
                                    onClick={prevMonth}
                                    className="p-2 hover:bg-gray-100 rounded-full transition-colors"
                                >
                                    <ChevronLeft size={24} />
                                </button>
                                <button
                                    onClick={() => setShowYearMonthPicker(!showYearMonthPicker)}
                                    className="flex items-center gap-1 text-xl font-bold hover:text-primary transition-colors"
                                >
                                    <span>{year}년 {month + 1}월</span>
                                    <ChevronDown size={20} className={`transition-transform ${showYearMonthPicker ? 'rotate-180' : ''}`} />
                                </button>
                                <button
                                    onClick={nextMonth}
                                    className="p-2 hover:bg-gray-100 rounded-full transition-colors"
                                >
                                    <ChevronRight size={24} />
                                </button>
                            </div>

                            {/* 년/월 선택 팝업 - 달력 카드 중앙 정렬 */}
                            <AnimatePresence>
                                {showYearMonthPicker && (
                                    <motion.div
                                        initial={{ opacity: 0, y: -10 }}
                                        animate={{ opacity: 1, y: 0 }}
                                        exit={{ opacity: 0, y: -10 }}
                                        className="absolute top-20 left-8 right-8 mx-auto w-80 bg-white rounded-xl shadow-lg border border-gray-200 p-4 z-10"
                                    >
                                                {/* 헤더 - 년도 범위 이동 */}
                                                <div className="flex items-center justify-between mb-4">
                                                    <button
                                                        onClick={prevYearRange}
                                                        className="p-1.5 hover:bg-gray-100 rounded-lg transition-colors"
                                                    >
                                                        <ChevronLeft size={20} className="text-gray-600" />
                                                    </button>
                                                    <span className="font-medium text-gray-900">
                                                        {viewMode === 'yearMonth' ? `${yearRange[0]} - ${yearRange[yearRange.length - 1]}` : `${year}년`}
                                                    </span>
                                                    <button
                                                        onClick={nextYearRange}
                                                        className="p-1.5 hover:bg-gray-100 rounded-lg transition-colors"
                                                    >
                                                        <ChevronRight size={20} className="text-gray-600" />
                                                    </button>
                                                </div>

                                                <AnimatePresence mode="wait">
                                                    {viewMode === 'yearMonth' && (
                                                        <motion.div
                                                            key="yearMonth"
                                                            initial={{ opacity: 0 }}
                                                            animate={{ opacity: 1 }}
                                                            exit={{ opacity: 0 }}
                                                            transition={{ duration: 0.15 }}
                                                        >
                                                            {/* 년도 선택 */}
                                                            <div className="text-center text-sm text-gray-500 mb-3">년도</div>
                                                            <div className="grid grid-cols-4 gap-2 mb-4">
                                                                {yearRange.map((y) => (
                                                                    <button
                                                                        key={y}
                                                                        onClick={() => selectYear(y)}
                                                                        className={`py-2 text-sm rounded-lg transition-colors ${
                                                                            year === y
                                                                                ? 'bg-primary text-white'
                                                                                : isCurrentYear(y) && year !== y
                                                                                    ? 'border border-primary text-primary hover:bg-primary/10'
                                                                                    : 'hover:bg-gray-100 text-gray-700'
                                                                        }`}
                                                                    >
                                                                        {y}
                                                                    </button>
                                                                ))}
                                                            </div>

                                                            {/* 월 선택 */}
                                                            <div className="text-center text-sm text-gray-500 mb-3">월</div>
                                                            <div className="grid grid-cols-4 gap-2">
                                                                {monthNames.map((m, i) => (
                                                                    <button
                                                                        key={m}
                                                                        onClick={() => selectMonth(i)}
                                                                        className={`py-2 text-sm rounded-lg transition-colors ${
                                                                            month === i
                                                                                ? 'bg-primary text-white'
                                                                                : isCurrentMonth(i) && month !== i
                                                                                    ? 'border border-primary text-primary hover:bg-primary/10'
                                                                                    : 'hover:bg-gray-100 text-gray-700'
                                                                        }`}
                                                                    >
                                                                        {m}
                                                                    </button>
                                                                ))}
                                                            </div>
                                                        </motion.div>
                                                    )}

                                                    {viewMode === 'months' && (
                                                        <motion.div
                                                            key="months"
                                                            initial={{ opacity: 0 }}
                                                            animate={{ opacity: 1 }}
                                                            exit={{ opacity: 0 }}
                                                            transition={{ duration: 0.15 }}
                                                        >
                                                            {/* 월 선택 */}
                                                            <div className="text-center text-sm text-gray-500 mb-3">월 선택</div>
                                                            <div className="grid grid-cols-4 gap-2">
                                                                {monthNames.map((m, i) => (
                                                                    <button
                                                                        key={m}
                                                                        onClick={() => selectMonth(i)}
                                                                        className={`py-2.5 text-sm rounded-lg transition-colors ${
                                                                            month === i
                                                                                ? 'bg-primary text-white'
                                                                                : isCurrentMonth(i) && month !== i
                                                                                    ? 'border border-primary text-primary hover:bg-primary/10'
                                                                                    : 'hover:bg-gray-100 text-gray-700'
                                                                        }`}
                                                                    >
                                                                        {m}
                                                                    </button>
                                                                ))}
                                                            </div>
                                                        </motion.div>
                                                    )}
                                                </AnimatePresence>
                                    </motion.div>
                                )}
                            </AnimatePresence>

                            {/* 요일 헤더 + 날짜 그리드 (함께 슬라이드) */}
                            <AnimatePresence mode="wait" initial={false}>
                                <motion.div
                                    key={`${year}-${month}`}
                                    initial={{ opacity: 0, x: slideDirection * 20 }}
                                    animate={{ opacity: 1, x: 0 }}
                                    exit={{ opacity: 0, x: slideDirection * -20 }}
                                    transition={{ duration: 0.08 }}
                                    layout
                                >
                                    {/* 요일 헤더 */}
                                    <div className="grid grid-cols-7 mb-4">
                                        {days.map((day, i) => (
                                            <div
                                                key={day}
                                                className={`text-center text-sm font-medium py-2 ${
                                                    i === 0 ? 'text-red-500' : i === 6 ? 'text-blue-500' : 'text-gray-500'
                                                }`}
                                            >
                                                {day}
                                            </div>
                                        ))}
                                    </div>

                                    {/* 날짜 그리드 */}
                                    <div className="grid grid-cols-7 gap-1">
                                {/* 전달 날짜 */}
                                {Array.from({ length: firstDay }).map((_, i) => {
                                    const prevMonthDays = getDaysInMonth(year, month - 1);
                                    const day = prevMonthDays - firstDay + i + 1;
                                    return (
                                        <div key={`prev-${i}`} className="aspect-square flex items-center justify-center text-gray-300 text-base">
                                            {day}
                                        </div>
                                    );
                                })}

                                {/* 현재 달 날짜 */}
                                {Array.from({ length: daysInMonth }).map((_, i) => {
                                    const day = i + 1;
                                    const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
                                    const isSelected = selectedDate === dateStr;
                                    const hasEvent = hasSchedule(day);
                                    const dayOfWeek = (firstDay + i) % 7;
                                    const isToday = new Date().toDateString() === new Date(year, month, day).toDateString();

                                    return (
                                        <button
                                            key={day}
                                            onClick={() => selectDate(day)}
                                            className={`aspect-square flex flex-col items-center justify-center rounded-full text-base font-medium transition-all relative hover:bg-gray-100
                                                ${isSelected ? 'bg-primary text-white shadow-lg hover:bg-primary' : ''}
                                                ${isToday && !isSelected ? 'bg-primary/10 text-primary font-bold hover:bg-primary/20' : ''}
                                                ${dayOfWeek === 0 && !isSelected && !isToday ? 'text-red-500' : ''}
                                                ${dayOfWeek === 6 && !isSelected && !isToday ? 'text-blue-500' : ''}
                                            `}
                                        >
                                            <span>{day}</span>
                                            {hasEvent && (
                                                <span className={`w-1.5 h-1.5 rounded-full mt-0.5 ${isSelected ? 'bg-white' : 'bg-primary'}`} />
                                            )}
                                        </button>
                                    );
                                })}

                                {/* 다음달 날짜 (마지막 주만 채우기) */}
                                {(() => {
                                    const totalCells = firstDay + daysInMonth;
                                    const remainder = totalCells % 7;
                                    const nextDays = remainder === 0 ? 0 : 7 - remainder;
                                    return Array.from({ length: nextDays }).map((_, i) => (
                                        <div key={`next-${i}`} className="aspect-square flex items-center justify-center text-gray-300 text-base">
                                            {i + 1}
                                        </div>
                                    ));
                                })()}
                                    </div>
                                </motion.div>
                            </AnimatePresence>

                            {/* 범례 및 전체보기 */}
                            <div className="mt-6 pt-4 border-t border-gray-100 flex items-center justify-between text-sm">
                                <div className="flex items-center gap-1.5 text-gray-500">
                                    <span className="w-2 h-2 rounded-full bg-primary flex-shrink-0" />
                                    <span className="leading-none">일정 있음</span>
                                </div>
                                <button
                                    onClick={() => setSelectedDate(null)}
                                    className={`px-4 py-2 rounded-lg transition-colors ${
                                        selectedDate 
                                            ? 'bg-primary text-white hover:bg-primary-dark' 
                                            : 'bg-gray-100 text-gray-400 cursor-default'
                                    }`}
                                    disabled={!selectedDate}
                                >
                                    전체 보기
                                </button>
                            </div>
                        </div>
                    </motion.div>

                    {/* 스케줄 리스트 */}
                    <div className="flex-1 space-y-4">
                        {filteredSchedules.length > 0 ? (
                            filteredSchedules.map((schedule, index) => {
                                const formatted = formatDate(schedule.date);
                                return (
                                    <motion.div
                                        key={schedule.id}
                                        initial={{ opacity: 0, y: 20 }}
                                        animate={{ opacity: 1, y: 0 }}
                                        transition={{ delay: index * 0.1 }}
                                        className="flex items-stretch bg-white rounded-2xl shadow-sm hover:shadow-md transition-shadow overflow-hidden"
                                    >
                                        {/* 날짜 영역 */}
                                        <div className="w-24 bg-primary flex flex-col items-center justify-center text-white py-6">
                                            <span className="text-sm font-medium opacity-80">{formatted.month}월</span>
                                            <span className="text-3xl font-bold">{formatted.day}</span>
                                            <span className="text-sm font-medium opacity-80">{formatted.weekday}</span>
                                        </div>

                                        {/* 스케줄 내용 */}
                                        <div className="flex-1 p-6 flex flex-col justify-center">
                                            <h3 className="font-bold text-lg mb-3">{schedule.title}</h3>
                                            
                                            <div className="flex flex-wrap gap-4 text-sm text-gray-500">
                                                <div className="flex items-center gap-1">
                                                    <Clock size={14} className="text-primary" />
                                                    <span>{schedule.time}</span>
                                                </div>
                                                <div className="flex items-center gap-1">
                                                    <MapPin size={14} className="text-primary" />
                                                    <span>{schedule.platform}</span>
                                                </div>
                                                <div className="flex items-center gap-1">
                                                    <Users size={14} className="text-primary" />
                                                    <span>{schedule.members.join(', ')}</span>
                                                </div>
                                            </div>
                                        </div>
                                    </motion.div>
                                );
                            })
                        ) : (
                            <div className="text-center py-20 text-gray-500">
                                {selectedDate ? '선택한 날짜에 일정이 없습니다.' : '예정된 일정이 없습니다.'}
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
}

export default Schedule;
