import React, { useState, useMemo, useEffect, useRef } from 'react';
import { useMockStore } from '../data/mockStore';
import { useTheme } from '../context/ThemeContext';
import { Calendar, User, Clock, MapPin, MoreHorizontal, Filter, X, ChevronDown } from 'lucide-react';
import { SpotlightCard } from '../components/SpotlightCard';

const AdminSchedule = () => {
    const { meetings } = useMockStore();
    const { theme } = useTheme();

    // Refs for click-outside detection
    const dateDropdownRef = useRef(null);
    const statusDropdownRef = useRef(null);

    // Filter states
    const [dateFilter, setDateFilter] = useState('all'); // all, today, week, month, quarter, custom
    const [customDateRange, setCustomDateRange] = useState({ start: '', end: '' });
    const [statusFilter, setStatusFilter] = useState([]);
    const [showDateDropdown, setShowDateDropdown] = useState(false);
    const [showStatusDropdown, setShowStatusDropdown] = useState(false);
    const [openDropdownId, setOpenDropdownId] = useState(null);

    // Click-outside detection for filter dropdowns
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (dateDropdownRef.current && !dateDropdownRef.current.contains(event.target)) {
                setShowDateDropdown(false);
            }
            if (statusDropdownRef.current && !statusDropdownRef.current.contains(event.target)) {
                setShowStatusDropdown(false);
            }
        };

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

    // Click-outside detection for action dropdowns
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (openDropdownId && !event.target.closest('.action-dropdown-container')) {
                setOpenDropdownId(null);
            }
        };

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

    // Get unique statuses from meetings
    const availableStatuses = useMemo(() => {
        return [...new Set(meetings.map(m => m.status))];
    }, [meetings]);

    // Filter meetings based on selected filters
    const filteredMeetings = useMemo(() => {
        let filtered = [...meetings];

        // Date filtering
        if (dateFilter !== 'all') {
            const now = new Date();
            const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());

            filtered = filtered.filter(meeting => {
                const meetingDate = new Date(meeting.date);

                switch (dateFilter) {
                    case 'today':
                        return meetingDate.toDateString() === today.toDateString();
                    case 'week':
                        const weekStart = new Date(today);
                        weekStart.setDate(today.getDate() - today.getDay());
                        const weekEnd = new Date(weekStart);
                        weekEnd.setDate(weekStart.getDate() + 6);
                        return meetingDate >= weekStart && meetingDate <= weekEnd;
                    case 'month':
                        return meetingDate.getMonth() === now.getMonth() &&
                            meetingDate.getFullYear() === now.getFullYear();
                    case 'quarter':
                        const quarter = Math.floor(now.getMonth() / 3);
                        const meetingQuarter = Math.floor(meetingDate.getMonth() / 3);
                        return meetingQuarter === quarter &&
                            meetingDate.getFullYear() === now.getFullYear();
                    case 'custom':
                        if (customDateRange.start && customDateRange.end) {
                            const start = new Date(customDateRange.start);
                            const end = new Date(customDateRange.end);
                            return meetingDate >= start && meetingDate <= end;
                        }
                        return true;
                    default:
                        return true;
                }
            });
        }

        // Status filtering
        if (statusFilter.length > 0) {
            filtered = filtered.filter(meeting => statusFilter.includes(meeting.status));
        }

        return filtered;
    }, [meetings, dateFilter, customDateRange, statusFilter]);

    const toggleStatusFilter = (status) => {
        setStatusFilter(prev =>
            prev.includes(status)
                ? prev.filter(s => s !== status)
                : [...prev, status]
        );
    };

    const clearFilters = () => {
        setDateFilter('all');
        setCustomDateRange({ start: '', end: '' });
        setStatusFilter([]);
    };

    const handleActionClick = (meetingId, action) => {
        console.log(`Action ${action} for meeting ${meetingId}`);
        // TODO: Implement actual actions
        setOpenDropdownId(null);
    };

    const [viewMode, setViewMode] = useState('list'); // 'list' or 'calendar'

    // Mock color mapping for agents
    const agentColors = {
        'a1': 'bg-blue-100 text-blue-700 border-blue-200 dark:bg-blue-900/30 dark:text-blue-300 dark:border-blue-800',
        'a2': 'bg-emerald-100 text-emerald-700 border-emerald-200 dark:bg-emerald-900/30 dark:text-emerald-300 dark:border-emerald-800',
        'a3': 'bg-purple-100 text-purple-700 border-purple-200 dark:bg-purple-900/30 dark:text-purple-300 dark:border-purple-800',
        'a4': 'bg-amber-100 text-amber-700 border-amber-200 dark:bg-amber-900/30 dark:text-amber-300 dark:border-amber-800',
        'a5': 'bg-pink-100 text-pink-700 border-pink-200 dark:bg-pink-900/30 dark:text-pink-300 dark:border-pink-800',
    };

    const getAgentColor = (agentId) => {
        // Simple hash or lookup
        const id = agentId?.toLowerCase() || 'a1';
        return agentColors[id] || agentColors['a1'];
    };

    return (
        <div className="min-h-full bg-zinc-50 dark:bg-[#09090b] text-zinc-900 dark:text-white selection:bg-blue-500/30 relative pb-20 transition-colors duration-300">
            {/* Ambient Background Glows */}
            <div className="fixed top-0 left-0 w-full h-full overflow-hidden pointer-events-none z-0">
                <div className="absolute top-[-10%] left-[-10%] w-[50%] h-[50%] bg-purple-500/5 dark:bg-purple-900/10 rounded-full blur-[120px]" />
                <div className="absolute bottom-[-10%] right-[-10%] w-[50%] h-[50%] bg-blue-500/5 dark:bg-blue-900/10 rounded-full blur-[120px]" />
            </div>

            {/* Content */}
            <div className="relative z-10 p-8 max-w-7xl mx-auto space-y-8">
                <header className="flex justify-between items-end">
                    <div>
                        <h1 className="text-4xl font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-zinc-900 to-zinc-600 dark:from-white dark:to-white/60 mb-2 tracking-tight">Team Schedule</h1>
                        <p className="text-zinc-600 dark:text-zinc-400">Manage field agent appointments</p>
                    </div>

                    {/* View Toggle */}
                    <div className="flex bg-zinc-100 dark:bg-zinc-800 p-1 rounded-xl border border-zinc-200 dark:border-zinc-700">
                        <button
                            onClick={() => setViewMode('list')}
                            className={`px-4 py-2 rounded-lg text-sm font-bold transition-all ${viewMode === 'list'
                                ? 'bg-white dark:bg-zinc-700 text-zinc-900 dark:text-white shadow-sm'
                                : 'text-zinc-500 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-white'
                                }`}
                        >
                            List View
                        </button>
                        <button
                            onClick={() => setViewMode('calendar')}
                            className={`px-4 py-2 rounded-lg text-sm font-bold transition-all ${viewMode === 'calendar'
                                ? 'bg-white dark:bg-zinc-700 text-zinc-900 dark:text-white shadow-sm'
                                : 'text-zinc-500 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-white'
                                }`}
                        >
                            Calendar View
                        </button>
                    </div>
                </header>

                {/* Filters Section (Only show relevant filters for list view potentially, or both) */}
                <div className="flex flex-wrap gap-4 items-center">
                    {/* Date Filter */}
                    <div className="relative" ref={dateDropdownRef}>
                        <button
                            onClick={() => setShowDateDropdown(!showDateDropdown)}
                            className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-white/[0.04] border border-zinc-200 dark:border-white/10 rounded-lg text-sm font-medium text-zinc-700 dark:text-zinc-200 hover:bg-zinc-50 dark:hover:bg-white/[0.07] transition-colors"
                        >
                            <Calendar size={16} />
                            {dateFilter === 'all' ? 'All Dates' :
                                dateFilter === 'today' ? 'Today' :
                                    dateFilter === 'week' ? 'This Week' :
                                        dateFilter === 'month' ? 'This Month' :
                                            dateFilter === 'quarter' ? 'This Quarter' :
                                                'Custom Range'}
                            <ChevronDown size={16} />
                        </button>

                        {showDateDropdown && (
                            <div className="absolute top-full mt-2 left-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700/50 rounded-lg backdrop-blur-xl shadow-2xl z-50 min-w-[200px]">
                                <button
                                    onClick={() => { setDateFilter('all'); setShowDateDropdown(false); }}
                                    className="w-full text-left px-4 py-2 text-sm text-zinc-700 dark:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
                                >
                                    All Dates
                                </button>
                                <button
                                    onClick={() => { setDateFilter('today'); setShowDateDropdown(false); }}
                                    className="w-full text-left px-4 py-2 text-sm text-zinc-700 dark:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
                                >
                                    Today
                                </button>
                                <button
                                    onClick={() => { setDateFilter('week'); setShowDateDropdown(false); }}
                                    className="w-full text-left px-4 py-2 text-sm text-zinc-700 dark:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
                                >
                                    This Week
                                </button>
                                <button
                                    onClick={() => { setDateFilter('month'); setShowDateDropdown(false); }}
                                    className="w-full text-left px-4 py-2 text-sm text-zinc-700 dark:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
                                >
                                    This Month
                                </button>
                                <button
                                    onClick={() => { setDateFilter('quarter'); setShowDateDropdown(false); }}
                                    className="w-full text-left px-4 py-2 text-sm text-zinc-700 dark:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
                                >
                                    This Quarter
                                </button>
                                <div className="border-t border-zinc-200 dark:border-zinc-700/50 p-3">
                                    <p className="text-xs font-semibold text-zinc-500 dark:text-zinc-400 mb-2">Custom Range</p>
                                    <label htmlFor="custom-date-start" className="sr-only">Start Date</label>
                                    <input
                                        id="custom-date-start"
                                        name="custom-date-start"
                                        type="date"
                                        value={customDateRange.start}
                                        onChange={(e) => setCustomDateRange(prev => ({ ...prev, start: e.target.value }))}
                                        className="w-full px-2 py-1 text-xs bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 rounded mb-2 text-zinc-900 dark:text-white"
                                        placeholder="Start date"
                                    />
                                    <label htmlFor="custom-date-end" className="sr-only">End Date</label>
                                    <input
                                        id="custom-date-end"
                                        name="custom-date-end"
                                        type="date"
                                        value={customDateRange.end}
                                        onChange={(e) => setCustomDateRange(prev => ({ ...prev, end: e.target.value }))}
                                        className="w-full px-2 py-1 text-xs bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 rounded mb-2 text-zinc-900 dark:text-white"
                                        placeholder="End date"
                                    />
                                    <button
                                        onClick={() => { setDateFilter('custom'); setShowDateDropdown(false); }}
                                        disabled={!customDateRange.start || !customDateRange.end}
                                        className="w-full px-2 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
                                    >
                                        Apply
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>

                    {/* Status Filter */}
                    <div className="relative" ref={statusDropdownRef}>
                        <button
                            onClick={() => setShowStatusDropdown(!showStatusDropdown)}
                            className="flex items-center gap-2 px-4 py-2 bg-white dark:bg-white/[0.04] border border-zinc-200 dark:border-white/10 rounded-lg text-sm font-medium text-zinc-700 dark:text-zinc-200 hover:bg-zinc-50 dark:hover:bg-white/[0.07] transition-colors"
                        >
                            <Filter size={16} />
                            Status {statusFilter.length > 0 && `(${statusFilter.length})`}
                            <ChevronDown size={16} />
                        </button>

                        {showStatusDropdown && (
                            <div className="absolute top-full mt-2 left-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700/50 rounded-lg backdrop-blur-xl shadow-2xl z-50 min-w-[200px]">
                                {availableStatuses.map(status => (
                                    <label
                                        key={status}
                                        htmlFor={`status-filter-${status.replace(/\s+/g, '-')}`}
                                        className="flex items-center gap-2 px-4 py-2 text-sm text-zinc-700 dark:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 cursor-pointer transition-colors"
                                    >
                                        <input
                                            id={`status-filter-${status.replace(/\s+/g, '-')}`}
                                            name={`status-filter-${status.replace(/\s+/g, '-')}`}
                                            type="checkbox"
                                            checked={statusFilter.includes(status)}
                                            onChange={() => toggleStatusFilter(status)}
                                            className="rounded border-zinc-300 dark:border-zinc-600"
                                        />
                                        {status}
                                    </label>
                                ))}
                            </div>
                        )}
                    </div>

                    {/* Clear Filters */}
                    {(dateFilter !== 'all' || statusFilter.length > 0) && (
                        <button
                            onClick={clearFilters}
                            className="flex items-center gap-2 px-4 py-2 text-sm font-medium text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
                        >
                            <X size={16} />
                            Clear Filters
                        </button>
                    )}

                    {/* Results Count */}
                    <div className="ml-auto text-sm text-zinc-600 dark:text-zinc-400">
                        Showing {filteredMeetings.length} of {meetings.length} appointments
                    </div>
                </div>

                <SpotlightCard className="overflow-hidden">
                    <div className="p-6 border-b border-zinc-200 dark:border-zinc-800">
                        <h2 className="text-xl font-bold text-zinc-900 dark:text-white flex items-center">
                            <Calendar size={20} className="text-blue-500 mr-2" />
                            {viewMode === 'list' ? 'All Active Appointments' : 'Calendar Overview'}
                        </h2>
                    </div>

                    {viewMode === 'list' ? (
                        <div className="overflow-x-auto">
                            <table className="w-full text-left text-sm text-zinc-600 dark:text-zinc-400">
                                <thead className="bg-zinc-100 dark:bg-zinc-950 text-zinc-700 dark:text-zinc-200 uppercase font-bold text-xs">
                                    <tr>
                                        <th className="px-6 py-4 min-w-[150px]">Agent</th>
                                        <th className="px-6 py-4 min-w-[180px]">Customer</th>
                                        <th className="px-6 py-4 min-w-[120px]">Property</th>
                                        <th className="px-6 py-4 min-w-[160px]">Date & Time</th>
                                        <th className="px-6 py-4 min-w-[120px]">Status</th>
                                        <th className="px-6 py-4 text-right min-w-[150px]">Actions</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-zinc-200 dark:divide-zinc-800">
                                    {filteredMeetings.length === 0 ? (
                                        <tr>
                                            <td colSpan="6" className="px-6 py-12 text-center text-zinc-500 dark:text-zinc-400">
                                                No appointments found matching the selected filters.
                                            </td>
                                        </tr>
                                    ) : (
                                        filteredMeetings.map((meeting) => (
                                            <tr key={meeting.id} className="hover:bg-zinc-50 dark:hover:bg-white/[0.03] transition-colors">
                                                <td className="px-6 py-4">
                                                    <div className="flex items-center space-x-3">
                                                        <div className={`w-8 h-8 rounded-full flex items-center justify-center font-bold text-xs ${getAgentColor(meeting.agentId)}`}>
                                                            {meeting.agentId}
                                                        </div>
                                                        <span className="font-medium text-zinc-900 dark:text-zinc-200 whitespace-normal">Agent {meeting.agentId}</span>
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4 text-zinc-900 dark:text-zinc-300 whitespace-normal">{meeting.customerName}</td>
                                                <td className="px-6 py-4 text-zinc-700 dark:text-zinc-400">{meeting.propertyId}</td>
                                                <td className="px-6 py-4">
                                                    <div className="flex flex-col">
                                                        <span className="text-zinc-900 dark:text-zinc-200">{meeting.date}</span>
                                                        <span className="text-xs text-zinc-600 dark:text-zinc-400">{meeting.time}</span>
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4">
                                                    <span className={`px-2 py-1 text-xs font-semibold rounded whitespace-nowrap ${meeting.status === 'Completed' ? 'bg-green-500/20 text-green-600 dark:text-green-400' :
                                                        meeting.status === 'Scheduled' ? 'bg-blue-500/20 text-blue-600 dark:text-blue-400' :
                                                            meeting.status === 'Converted' ? 'bg-purple-500/20 text-purple-600 dark:text-purple-400' :
                                                                meeting.status === 'Cancelled' ? 'bg-red-500/20 text-red-600 dark:text-red-400' :
                                                                    'bg-yellow-500/20 text-yellow-600 dark:text-yellow-400'
                                                        }`}>
                                                        {meeting.status}
                                                    </span>
                                                </td>
                                                <td className="px-6 py-4 text-right">
                                                    <div className="flex items-center justify-end gap-3">
                                                        <button className="text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300 text-xs font-bold">
                                                            Reschedule
                                                        </button>
                                                        <div className="relative action-dropdown-container">
                                                            <button
                                                                onClick={() => setOpenDropdownId(openDropdownId === meeting.id ? null : meeting.id)}
                                                                className="text-zinc-600 dark:text-zinc-400 hover:text-zinc-900 dark:hover:text-zinc-200 transition-colors"
                                                            >
                                                                <MoreHorizontal size={16} />
                                                            </button>

                                                            {openDropdownId === meeting.id && (
                                                                <div className="absolute right-0 top-full mt-1 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700/50 rounded-lg backdrop-blur-xl shadow-2xl z-50 min-w-[160px]">
                                                                    <button
                                                                        onClick={() => handleActionClick(meeting.id, 'view')}
                                                                        className="w-full text-left px-4 py-2 text-sm text-zinc-700 dark:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
                                                                    >
                                                                        View Details
                                                                    </button>
                                                                    <button
                                                                        onClick={() => handleActionClick(meeting.id, 'reschedule')}
                                                                        className="w-full text-left px-4 py-2 text-sm text-zinc-700 dark:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
                                                                    >
                                                                        Reschedule
                                                                    </button>
                                                                    <button
                                                                        onClick={() => handleActionClick(meeting.id, 'complete')}
                                                                        className="w-full text-left px-4 py-2 text-sm text-zinc-700 dark:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors"
                                                                    >
                                                                        Mark Complete
                                                                    </button>
                                                                    <button
                                                                        onClick={() => handleActionClick(meeting.id, 'cancel')}
                                                                        className="w-full text-left px-4 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
                                                                    >
                                                                        Cancel
                                                                    </button>
                                                                </div>
                                                            )}
                                                        </div>
                                                    </div>
                                                </td>
                                            </tr>
                                        ))
                                    )}
                                </tbody>
                            </table>
                        </div>
                    ) : (
                        <CalendarView meetings={filteredMeetings} getAgentColor={getAgentColor} />
                    )}
                </SpotlightCard>
            </div>
            <span className="attribution-ghost">igotsar.matyas | LynkedUpPro - Turns out roofing CRMs don't build themselves. Who knew?</span>
        </div>
    );
};

// --- Custom Month View Calendar ---
const CalendarView = ({ meetings, getAgentColor }) => {
    // Current month view state
    const [currentDate, setCurrentDate] = useState(new Date());

    const getDaysInMonth = (date) => {
        const year = date.getFullYear();
        const month = date.getMonth();
        const days = new Date(year, month + 1, 0).getDate();
        const firstDay = new Date(year, month, 1).getDay();
        return { days, firstDay };
    };

    const { days, firstDay } = useMemo(() => getDaysInMonth(currentDate), [currentDate]);

    const changeMonth = (offset) => {
        setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() + offset, 1));
    };

    // Group meetings by date (using local date string YYYY-MM-DD)
    const meetingsByDate = useMemo(() => {
        const map = {};
        meetings.forEach(m => {
            // Assuming m.date is YYYY-MM-DD or parseable
            const d = new Date(m.date);
            // We need to compare local dates
            const key = d.getDate(); // 1-31
            const monthMatches = d.getMonth() === currentDate.getMonth() && d.getFullYear() === currentDate.getFullYear();

            if (monthMatches) {
                if (!map[key]) map[key] = [];
                map[key].push(m);
            }
        });
        return map;
    }, [meetings, currentDate]);

    const renderCalendarCells = () => {
        const cells = [];
        // Empty cells for padding before the first day
        for (let i = 0; i < firstDay; i++) {
            cells.push(<div key={`empty-${i}`} className="h-32 bg-zinc-50/50 dark:bg-zinc-900/30 border-r border-b border-zinc-200 dark:border-zinc-800"></div>);
        }

        // Days
        for (let d = 1; d <= days; d++) {
            const dayMeetings = meetingsByDate[d] || [];
            const isToday = new Date().toDateString() === new Date(currentDate.getFullYear(), currentDate.getMonth(), d).toDateString();

            cells.push(
                <div key={`day-${d}`} className={`group h-32 p-2 border-r border-b border-zinc-200 dark:border-zinc-800 hover:bg-zinc-50 dark:hover:bg-white/5 transition-colors relative overflow-y-auto custom-scrollbar ${isToday ? 'bg-blue-50/30 dark:bg-blue-500/5' : ''}`}>
                    <div className="flex justify-between items-start mb-1">
                        <span className={`text-sm font-bold w-6 h-6 flex items-center justify-center rounded-full ${isToday ? 'bg-blue-500 text-white' : 'text-zinc-500 dark:text-zinc-400'}`}>
                            {d}
                        </span>
                    </div>
                    <div className="space-y-1">
                        {dayMeetings.map(m => (
                            <div
                                key={m.id}
                                className={`text-[10px] truncate px-1.5 py-1 rounded border shadow-sm cursor-pointer hover:opacity-80 ${getAgentColor(m.agentId)}`}
                                title={`${m.time} - ${m.customerName} (${m.status})`}
                            >
                                <span className="font-bold mr-1">{m.time}</span>
                                {m.customerName}
                            </div>
                        ))}
                    </div>
                </div>
            );
        }
        return cells;
    };

    return (
        <div className="p-4">
            {/* Calendar Header */}
            <div className="flex items-center justify-between mb-6">
                <h3 className="text-xl font-bold text-zinc-900 dark:text-white capitalize">
                    {currentDate.toLocaleDateString('en-US', { month: 'long', year: 'numeric' })}
                </h3>
                <div className="flex gap-2">
                    <button onClick={() => changeMonth(-1)} className="p-2 rounded-lg bg-zinc-100 dark:bg-zinc-800 hover:bg-zinc-200 dark:hover:bg-zinc-700 transition-colors">Before</button>
                    <button onClick={() => setCurrentDate(new Date())} className="px-4 py-2 rounded-lg bg-blue-500 text-white text-sm font-bold hover:bg-blue-600 transition-colors">Today</button>
                    <button onClick={() => changeMonth(1)} className="p-2 rounded-lg bg-zinc-100 dark:bg-zinc-800 hover:bg-zinc-200 dark:hover:bg-zinc-700 transition-colors">Next</button>
                </div>
            </div>

            {/* Calendar Grid */}
            <div className="border-t border-l border-zinc-200 dark:border-zinc-800 rounded-lg overflow-hidden">
                {/* Weekday Headers */}
                <div className="grid grid-cols-7 bg-zinc-50 dark:bg-zinc-900 border-b border-zinc-200 dark:border-zinc-800">
                    {['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map(day => (
                        <div key={day} className="py-2 text-center text-xs font-bold uppercase text-zinc-500 dark:text-zinc-400 border-r border-zinc-200 dark:border-zinc-800 last:border-r-0">
                            {day}
                        </div>
                    ))}
                </div>
                {/* Days Grid */}
                <div className="grid grid-cols-7 bg-white dark:bg-[#09090b]">
                    {renderCalendarCells()}
                </div>
            </div>

            {/* Legend */}
            <div className="mt-4 flex flex-wrap gap-4 text-xs text-zinc-500 dark:text-zinc-400">
                <div className="flex items-center gap-2"><div className="w-3 h-3 rounded bg-blue-100 border border-blue-200"></div> Agent A1</div>
                <div className="flex items-center gap-2"><div className="w-3 h-3 rounded bg-emerald-100 border border-emerald-200"></div> Agent A2</div>
                <div className="flex items-center gap-2"><div className="w-3 h-3 rounded bg-purple-100 border border-purple-200"></div> Agent A3</div>
                <div className="flex items-center gap-2"><div className="w-3 h-3 rounded bg-amber-100 border border-amber-200"></div> Agent A4</div>
                <div className="flex items-center gap-2"><div className="w-3 h-3 rounded bg-pink-100 border border-pink-200"></div> Agent A5</div>
            </div>
        </div>
    );
};

export default AdminSchedule;
