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

function Schedule() {
    const [currentDate, setCurrentDate] = useState(new Date());
    const [selectedDate, setSelectedDate] = useState(null);

    // 달력 관련 함수
    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 monthNames = ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'];

    // 스케줄이 있는 날짜 목록
    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 = () => {
        setCurrentDate(new Date(year, month - 1, 1));
        setSelectedDate(null);
    };

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

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

    // 필터링된 스케줄
    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()],
        };
    };

    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-80 flex-shrink-0"
                    >
                        <div className="bg-white rounded-2xl shadow-sm p-6">
                            {/* 달력 헤더 */}
                            <div className="flex items-center justify-between mb-6">
                                <button
                                    onClick={prevMonth}
                                    className="p-2 hover:bg-gray-100 rounded-full transition-colors"
                                >
                                    <ChevronLeft size={20} />
                                </button>
                                <h3 className="text-lg font-bold">
                                    {year}년 {monthNames[month]}
                                </h3>
                                <button
                                    onClick={nextMonth}
                                    className="p-2 hover:bg-gray-100 rounded-full transition-colors"
                                >
                                    <ChevronRight size={20} />
                                </button>
                            </div>

                            {/* 요일 헤더 */}
                            <div className="grid grid-cols-7 mb-2">
                                {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) => (
                                    <div key={`empty-${i}`} className="aspect-square" />
                                ))}

                                {/* 날짜 */}
                                {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={() => hasEvent && selectDate(day)}
                                            className={`aspect-square flex flex-col items-center justify-center rounded-lg text-sm transition-all
                                                ${isSelected ? 'bg-primary text-white' : ''}
                                                ${isToday && !isSelected ? 'ring-2 ring-primary' : ''}
                                                ${hasEvent && !isSelected ? 'hover:bg-primary/10 cursor-pointer' : ''}
                                                ${!hasEvent ? 'cursor-default' : ''}
                                                ${dayOfWeek === 0 && !isSelected ? 'text-red-500' : ''}
                                                ${dayOfWeek === 6 && !isSelected ? '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>
                                    );
                                })}
                            </div>

                            {/* 범례 */}
                            <div className="mt-4 pt-4 border-t border-gray-100 flex items-center justify-center gap-4 text-xs text-gray-500">
                                <div className="flex items-center gap-1">
                                    <span className="w-2 h-2 rounded-full bg-primary" />
                                    <span>일정 있음</span>
                                </div>
                                {selectedDate && (
                                    <button
                                        onClick={() => setSelectedDate(null)}
                                        className="text-primary hover:underline"
                                    >
                                        전체 보기
                                    </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">
                                            <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;
