import { useState, useEffect, useRef } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { 
    LogOut, Home, ChevronRight, Calendar, Plus, Edit2, Trash2,
    ChevronLeft, Search, ChevronDown, AlertTriangle
} from 'lucide-react';
import Toast from '../../../components/Toast';
import Tooltip from '../../../components/Tooltip';

function AdminSchedule() {
    const navigate = useNavigate();
    const [loading, setLoading] = useState(false);
    const [user, setUser] = useState(null);
    const [toast, setToast] = useState(null);
    const [searchTerm, setSearchTerm] = useState('');
    const [selectedCategories, setSelectedCategories] = useState([]); // 빈 배열 = 전체
    const [selectedDate, setSelectedDate] = useState(null);
    const [currentDate, setCurrentDate] = useState(new Date());
    const [slideDirection, setSlideDirection] = useState(0);
    
    // 년월 선택 관련 (Schedule.jsx와 동일한 패턴)
    const [showYearMonthPicker, setShowYearMonthPicker] = useState(false);
    const [viewMode, setViewMode] = useState('yearMonth'); // 'yearMonth' | 'months'
    const pickerRef = useRef(null);

    // 달력 관련
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();
    const firstDay = new Date(year, month, 1).getDay();
    const daysInMonth = new Date(year, month + 1, 0).getDate();
    const days = ['일', '월', '화', '수', '목', '금', '토'];
    const monthNames = ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'];
    
    // 년도 범위 (현재 년도 기준 10년 단위 - Schedule.jsx와 동일)
    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 getDaysInMonth = (y, m) => new Date(y, m + 1, 0).getDate();

    // 카테고리 목록 (API에서 로드)
    const [categories, setCategories] = useState([
        { id: 'all', name: '전체', color: 'gray' }
    ]);
    
    // 일정 목록 (API에서 로드)
    const [schedules, setSchedules] = useState([]);

    // 카테고리 색상 맵핑
    const colorMap = {
        blue: 'bg-blue-500',
        green: 'bg-green-500',
        purple: 'bg-purple-500',
        red: 'bg-red-500',
        pink: 'bg-pink-500',
        yellow: 'bg-yellow-500',
        orange: 'bg-orange-500',
        gray: 'bg-gray-500',
    };

    // 색상 스타일 (기본 색상 또는 커스텀 HEX)
    const getColorStyle = (color) => {
        if (!color) return { className: 'bg-gray-500' };
        if (color.startsWith('#')) {
            return { style: { backgroundColor: color } };
        }
        return { className: colorMap[color] || 'bg-gray-500' };
    };

    // 카테고리별 색상 (배지용)
    const getCategoryColor = (color) => {
        const colors = {
            blue: 'bg-blue-100 text-blue-700',
            green: 'bg-green-100 text-green-700',
            purple: 'bg-purple-100 text-purple-700',
            red: 'bg-red-100 text-red-700',
            pink: 'bg-pink-100 text-pink-700',
            yellow: 'bg-yellow-100 text-yellow-700',
            orange: 'bg-orange-100 text-orange-700',
            gray: 'bg-gray-100 text-gray-700',
        };
        if (color?.startsWith('#')) {
            return 'bg-gray-100 text-gray-700';
        }
        return colors[color] || 'bg-gray-100 text-gray-700';
    };

    // 해당 날짜에 일정이 있는지 확인
    const hasSchedule = (day) => {
        const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
        return schedules.some(s => {
            const scheduleDate = new Date(s.date).toISOString().split('T')[0];
            return scheduleDate === dateStr;
        });
    };

    // Toast 자동 숨김
    useEffect(() => {
        if (toast) {
            const timer = setTimeout(() => setToast(null), 3000);
            return () => clearTimeout(timer);
        }
    }, [toast]);

    useEffect(() => {
        const token = localStorage.getItem('adminToken');
        const userData = localStorage.getItem('adminUser');

        if (!token || !userData) {
            navigate('/admin');
            return;
        }

        setUser(JSON.parse(userData));
        
        // 카테고리 로드
        fetchCategories();
    }, [navigate]);
    
    // 월이 변경될 때마다 일정 로드
    useEffect(() => {
        fetchSchedules();
    }, [year, month]);
    
    // 카테고리 로드 함수
    const fetchCategories = async () => {
        try {
            const res = await fetch('/api/admin/schedule-categories');
            const data = await res.json();
            setCategories([
                { id: 'all', name: '전체', color: 'gray' },
                ...data
            ]);
        } catch (error) {
            console.error('카테고리 로드 오류:', error);
        }
    };
    
    // 일정 로드 함수
    const fetchSchedules = async () => {
        setLoading(true);
        try {
            const res = await fetch(`/api/admin/schedules?year=${year}&month=${month + 1}`);
            const data = await res.json();
            setSchedules(data);
        } catch (error) {
            console.error('일정 로드 오류:', error);
        } finally {
            setLoading(false);
        }
    };

    // 외부 클릭 시 피커 닫기
    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 handleLogout = () => {
        localStorage.removeItem('adminToken');
        localStorage.removeItem('adminUser');
        navigate('/admin');
    };

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

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

    // 년도 범위 이동
    const prevYearRange = () => setCurrentDate(new Date(year - 10, month, 1));
    const nextYearRange = () => setCurrentDate(new Date(year + 10, month, 1));

    // 년도 선택 시 월 선택 모드로 전환
    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 selectDate = (day) => {
        const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
        setSelectedDate(selectedDate === dateStr ? null : dateStr);
    };
    
    // 전체보기
    const showAll = () => {
        setSelectedDate(null);
    };

    // 삭제 관련 상태
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [scheduleToDelete, setScheduleToDelete] = useState(null);
    const [deleting, setDeleting] = useState(false);

    // 삭제 확인 다이얼로그 열기
    const openDeleteDialog = (schedule) => {
        setScheduleToDelete(schedule);
        setDeleteDialogOpen(true);
    };

    // 일정 삭제
    const handleDelete = async () => {
        if (!scheduleToDelete) return;
        
        setDeleting(true);
        try {
            const token = localStorage.getItem('adminToken');
            const response = await fetch(`/api/admin/schedules/${scheduleToDelete.id}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${token}`,
                },
            });
            
            if (response.ok) {
                setToast({ type: 'success', message: '일정이 삭제되었습니다.' });
                fetchSchedules(); // 일정 목록 새로고침
            } else {
                const data = await response.json();
                setToast({ type: 'error', message: data.error || '삭제 실패' });
            }
        } catch (error) {
            console.error('삭제 오류:', error);
            setToast({ type: 'error', message: '삭제 중 오류가 발생했습니다.' });
        } finally {
            setDeleting(false);
            setDeleteDialogOpen(false);
            setScheduleToDelete(null);
        }
    };

    // 필터링된 일정
    const filteredSchedules = schedules.filter(schedule => {
        const matchesSearch = schedule.title.toLowerCase().includes(searchTerm.toLowerCase());
        // 카테고리 필터링: 빈 배열이면 전체, 아니면 선택된 카테고리들에 포함되는지 확인
        const matchesCategory = selectedCategories.length === 0 || selectedCategories.includes(schedule.category_id);
        // 날짜 필터링 추가
        const scheduleDate = new Date(schedule.date).toISOString().split('T')[0];
        const matchesDate = !selectedDate || scheduleDate === selectedDate;
        return matchesSearch && matchesCategory && matchesDate;
    });

    return (
        <div className="min-h-screen bg-gray-50">
            <Toast toast={toast} onClose={() => setToast(null)} />

            {/* 삭제 확인 다이얼로그 */}
            <AnimatePresence>
                {deleteDialogOpen && (
                    <motion.div
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
                        onClick={() => !deleting && setDeleteDialogOpen(false)}
                    >
                        <motion.div
                            initial={{ scale: 0.9, opacity: 0 }}
                            animate={{ scale: 1, opacity: 1 }}
                            exit={{ scale: 0.9, opacity: 0 }}
                            className="bg-white rounded-2xl p-6 max-w-md w-full mx-4 shadow-xl"
                            onClick={(e) => e.stopPropagation()}
                        >
                            <div className="flex items-center gap-3 mb-4">
                                <div className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
                                    <AlertTriangle className="text-red-500" size={20} />
                                </div>
                                <h3 className="text-lg font-bold text-gray-900">일정 삭제</h3>
                            </div>
                            
                            <p className="text-gray-600 mb-2">
                                다음 일정을 삭제하시겠습니까?
                            </p>
                            <p className="text-gray-900 font-medium mb-4 p-3 bg-gray-50 rounded-lg">
                                {scheduleToDelete?.title}
                            </p>
                            <p className="text-sm text-red-500 mb-6">
                                이 작업은 되돌릴 수 없습니다.
                            </p>
                            
                            <div className="flex justify-end gap-3">
                                <button
                                    type="button"
                                    onClick={() => setDeleteDialogOpen(false)}
                                    disabled={deleting}
                                    className="px-4 py-2 text-gray-600 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors disabled:opacity-50"
                                >
                                    취소
                                </button>
                                <button
                                    type="button"
                                    onClick={handleDelete}
                                    disabled={deleting}
                                    className="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors flex items-center gap-2 disabled:opacity-50"
                                >
                                    {deleting ? (
                                        <>
                                            <motion.div
                                                animate={{ rotate: 360 }}
                                                transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                                                className="w-4 h-4 border-2 border-white border-t-transparent rounded-full"
                                            />
                                            삭제 중...
                                        </>
                                    ) : (
                                        <>
                                            <Trash2 size={16} />
                                            삭제
                                        </>
                                    )}
                                </button>
                            </div>
                        </motion.div>
                    </motion.div>
                )}
            </AnimatePresence>

            {/* 헤더 */}
            <header className="bg-white shadow-sm border-b border-gray-100">
                <div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
                    <div className="flex items-center gap-4">
                        <Link to="/admin/dashboard" className="text-2xl font-bold text-primary hover:opacity-80 transition-opacity">
                            fromis_9
                        </Link>
                        <span className="px-3 py-1 bg-primary/10 text-primary text-sm font-medium rounded-full">
                            Admin
                        </span>
                    </div>
                    <div className="flex items-center gap-4">
                        <span className="text-gray-500 text-sm">
                            안녕하세요, <span className="text-gray-900 font-medium">{user?.username}</span>님
                        </span>
                        <button
                            onClick={handleLogout}
                            className="flex items-center gap-2 px-4 py-2 text-gray-500 hover:text-gray-900 hover:bg-gray-100 rounded-lg transition-colors"
                        >
                            <LogOut size={18} />
                            <span>로그아웃</span>
                        </button>
                    </div>
                </div>
            </header>

            {/* 메인 콘텐츠 */}
            <main className="max-w-7xl mx-auto px-6 py-8">
                {/* 브레드크럼 */}
                <div className="flex items-center gap-2 text-sm text-gray-400 mb-8">
                    <Link to="/admin/dashboard" className="hover:text-primary transition-colors">
                        <Home size={16} />
                    </Link>
                    <ChevronRight size={14} />
                    <span className="text-gray-700">일정 관리</span>
                </div>

                {/* 타이틀 + 추가 버튼 */}
                <div className="flex items-center justify-between mb-8">
                    <div>
                        <h1 className="text-3xl font-bold text-gray-900 mb-2">일정 관리</h1>
                        <p className="text-gray-500">fromis_9의 일정을 관리합니다</p>
                    </div>
                    <button
                        onClick={() => navigate('/admin/schedule/new')}
                        className="flex items-center gap-2 px-5 py-3 bg-primary text-white rounded-xl hover:bg-primary-dark transition-colors font-medium shadow-sm"
                    >
                        <Plus size={20} />
                        일정 추가
                    </button>
                </div>

                <div className="grid grid-cols-3 gap-8">
                    {/* 왼쪽: 달력 + 카테고리 필터 */}
                    <div className="space-y-6">
                        {/* 달력 (Schedule.jsx와 동일한 패턴) */}
                        <div ref={pickerRef} className="bg-white rounded-2xl shadow-sm pt-8 px-8 pb-6 relative">
                            {/* 달력 헤더 */}
                            <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>

                            {/* 년/월 선택 팝업 (Schedule.jsx와 동일한 스타일) */}
                            <AnimatePresence>
                                {showYearMonthPicker && (
                                    <motion.div
                                        initial={{ opacity: 0, y: -10 }}
                                        animate={{ opacity: 1, y: 0 }}
                                        exit={{ opacity: 0, y: -10 }}
                                        className="absolute top-16 left-6 right-6 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 }}
                                >
                                    {/* 요일 헤더 */}
                                    <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={showAll}
                                    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>

                        {/* 카테고리 필터 */}
                        <div className="bg-white rounded-2xl shadow-sm p-6">
                            <h3 className="font-bold text-gray-900 mb-4">카테고리</h3>
                            <div className="space-y-2">
                                {categories.map(category => {
                                    const isSelected = category.id === 'all' 
                                        ? selectedCategories.length === 0 
                                        : selectedCategories.includes(category.id);
                                    
                                    const handleClick = () => {
                                        if (category.id === 'all') {
                                            // 전체 클릭 시 모든 선택 해제
                                            setSelectedCategories([]);
                                        } else {
                                            // 개별 카테고리 클릭 시 토글
                                            if (selectedCategories.includes(category.id)) {
                                                setSelectedCategories(selectedCategories.filter(id => id !== category.id));
                                            } else {
                                                setSelectedCategories([...selectedCategories, category.id]);
                                            }
                                        }
                                    };
                                    
                                    return (
                                        <button
                                            key={category.id}
                                            onClick={handleClick}
                                            className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-left transition-colors ${
                                                isSelected
                                                    ? 'bg-primary/10 text-primary'
                                                    : 'hover:bg-gray-50 text-gray-700'
                                            }`}
                                        >
                                            <span 
                                                className={`w-3 h-3 rounded-full ${category.id === 'all' ? 'bg-gray-400' : (getColorStyle(category.color).className || '')}`}
                                                style={category.id !== 'all' ? getColorStyle(category.color).style : undefined}
                                            />
                                            <span className="font-medium">{category.name}</span>
                                            <span className="ml-auto text-sm text-gray-400">
                                                {category.id === 'all' 
                                                    ? schedules.length 
                                                    : schedules.filter(s => s.category_id === category.id).length
                                                }
                                            </span>
                                        </button>
                                    );
                                })}
                            </div>
                        </div>
                    </div>

                    {/* 오른쪽: 일정 목록 */}
                    <div className="col-span-2">
                        {/* 검색 */}
                        <div className="bg-white rounded-2xl shadow-sm p-4 mb-6">
                            <div className="relative">
                                <Search size={20} className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400" />
                                <input
                                    type="text"
                                    placeholder="일정 검색..."
                                    value={searchTerm}
                                    onChange={(e) => setSearchTerm(e.target.value)}
                                    className="w-full pl-12 pr-4 py-3 bg-gray-50 rounded-xl focus:outline-none focus:ring-2 focus:ring-primary focus:bg-white transition-all"
                                />
                            </div>
                        </div>

                        {/* 일정 목록 */}
                        <div className="bg-white rounded-2xl shadow-sm overflow-hidden">
                            <div className="p-6 border-b border-gray-100">
                                <div className="flex items-center justify-between">
                                    {selectedCategories.length > 1 ? (
                                        <Tooltip 
                                            text={
                                                <div className="flex flex-col gap-1.5">
                                                    {selectedCategories.map(id => {
                                                        const cat = categories.find(c => c.id === id);
                                                        if (!cat) return null;
                                                        return (
                                                            <div key={id} className="flex items-center gap-2">
                                                                <span 
                                                                    className={`w-2.5 h-2.5 rounded-full flex-shrink-0 ${getColorStyle(cat.color).className || ''}`}
                                                                    style={getColorStyle(cat.color).style}
                                                                />
                                                                <span>{cat.name}</span>
                                                            </div>
                                                        );
                                                    })}
                                                </div>
                                            }
                                        >
                                            <h3 className="font-bold text-gray-900">
                                                {`${selectedCategories.length}개 카테고리 선택됨`}
                                            </h3>
                                        </Tooltip>
                                    ) : (
                                        <h3 className="font-bold text-gray-900">
                                            {selectedCategories.length === 0 
                                                ? '전체 일정' 
                                                : categories.find(c => c.id === selectedCategories[0])?.name
                                            }
                                        </h3>
                                    )}
                                    <span className="text-sm text-gray-500">{filteredSchedules.length}개의 일정</span>
                                </div>
                            </div>

                            {loading ? (
                                <div className="flex justify-center items-center py-20">
                                    <div className="animate-spin rounded-full h-12 w-12 border-4 border-primary border-t-transparent"></div>
                                </div>
                            ) : filteredSchedules.length === 0 ? (
                                <div className="text-center py-16 text-gray-500">
                                    <Calendar size={48} className="mx-auto mb-4 text-gray-300" />
                                    <p>등록된 일정이 없습니다</p>
                                </div>
                            ) : (
                                <div className="divide-y divide-gray-100">
                                    {filteredSchedules.map((schedule, index) => (
                                        <motion.div
                                            key={schedule.id}
                                            initial={{ opacity: 0, y: 10 }}
                                            animate={{ opacity: 1, y: 0 }}
                                            transition={{ delay: index * 0.05 }}
                                            className="p-6 hover:bg-gray-50 transition-colors group"
                                        >
                                            <div className="flex items-start gap-4">
                                                {/* 날짜 */}
                                                <div className="w-16 text-center flex-shrink-0">
                                                    <div className="text-2xl font-bold text-gray-900">
                                                        {new Date(schedule.date).getDate()}
                                                    </div>
                                                    <div className="text-sm text-gray-500">
                                                        {new Date(schedule.date).toLocaleDateString('ko-KR', { weekday: 'short' })}
                                                    </div>
                                                </div>

                                                {/* 내용 */}
                                                <div className="flex-1 min-w-0">
                                                    <div className="flex items-center gap-2 mb-1">
                                                        <span className={`px-2 py-0.5 text-xs font-medium rounded-full ${getCategoryColor(schedule.category_color)}`}>
                                                            {schedule.category_name || '미지정'}
                                                        </span>
                                                        <span className="text-sm text-gray-400">{schedule.time?.slice(0, 5)}</span>
                                                    </div>
                                                    <h4 className="font-medium text-gray-900 mb-1">{schedule.title}</h4>
                                                    <p className="text-sm text-gray-500">{schedule.description}</p>
                                                </div>

                                                {/* 액션 버튼 */}
                                                <div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                                    <button 
                                                        onClick={() => navigate(`/admin/schedule/${schedule.id}/edit`)}
                                                        className="p-2 hover:bg-gray-200 rounded-lg transition-colors text-gray-500"
                                                    >
                                                        <Edit2 size={18} />
                                                    </button>
                                                    <button 
                                                        onClick={() => openDeleteDialog(schedule)}
                                                        className="p-2 hover:bg-red-100 rounded-lg transition-colors text-red-500"
                                                    >
                                                        <Trash2 size={18} />
                                                    </button>
                                                </div>
                                            </div>
                                        </motion.div>
                                    ))}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </main>
        </div>
    );
}

export default AdminSchedule;
