import GeneralHeader from '@admin/components/general-header';
import { AddEventModal } from '@admin/components/modals/AddEventModal';
import { EventDetailsModal } from '@admin/components/modals/EventDetailsModal';
import { Avatar, AvatarFallback, AvatarImage } from '@admin/components/ui/avatar';
import { Button } from '@admin/components/ui/button';
import { Card, CardContent, CardHeader } from '@admin/components/ui/card';
import { Checkbox } from '@admin/components/ui/checkbox';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@admin/components/ui/dropdown-menu';
import { Label } from '@admin/components/ui/label';
import AppLayout from '@admin/layouts/app-layout';
import { Head } from '@inertiajs/react';
import { Calendar as CalendarIcon, ChevronLeft, ChevronRight, Filter, MoreHorizontal, Plus } from 'lucide-react';
import { ReactNode, useEffect, useRef, useState } from 'react';

// Types based on the API response
interface CP {
    id: string;
    name: string;
    role: string;
    profile_picture?: string;
}

interface Client {
    id: string;
    name: string;
    role: string;
    profile_picture?: string;
}

interface Order {
    id: string;
    name: string;
}

interface ChangeRequest {
    requested_by?: string;
    request_type?: string;
    request_status: string;
    request_date_time?: string;
}

interface Event {
    id: string;
    meeting_status: string;
    meetLink: string;
    meeting_date_time: string;
    meeting_type: string;
    change_request: ChangeRequest;
    date_time_updates: any;
    order: Order;
    cps: CP[];
    createdAt: string;
    client: Client;
}

// Static data for demonstration
const staticEvents: Event[] = [
    {
        id: '1',
        meeting_status: 'pending',
        meetLink: 'https://meet.google.com/abc-def-ghi',
        meeting_date_time: new Date(2025, 9, 12, 11, 0).toISOString(), // Oct 12, 2025 11:00
        meeting_type: 'project_kickoff',
        change_request: {
            request_status: 'none',
        },
        date_time_updates: null,
        order: {
            id: 'order-1',
            name: 'Legacy Tactics Plan',
        },
        cps: [
            {
                id: 'cp-1',
                name: 'John Designer',
                role: 'Design Lead',
                profile_picture: '',
            },
            {
                id: 'cp-2',
                name: 'Sarah Manager',
                role: 'Project Manager',
                profile_picture: '',
            },
        ],
        createdAt: new Date().toISOString(),
        client: {
            id: 'client-1',
            name: 'Acme Corp',
            role: 'Marketing Director',
            profile_picture: '',
        },
    },
    {
        id: '2',
        meeting_status: 'completed',
        meetLink: 'https://meet.google.com/xyz-uvw-rst',
        meeting_date_time: new Date(2025, 9, 15, 14, 30).toISOString(), // Oct 15, 2025 14:30
        meeting_type: 'progress_review',
        change_request: {
            request_status: 'none',
        },
        date_time_updates: null,
        order: {
            id: 'order-2',
            name: 'Mobile App Development',
        },
        cps: [
            {
                id: 'cp-3',
                name: 'Mike Developer',
                role: 'Tech Lead',
                profile_picture: '',
            },
        ],
        createdAt: new Date().toISOString(),
        client: {
            id: 'client-2',
            name: 'Tech Solutions Inc',
            role: 'CTO',
            profile_picture: '',
        },
    },
    {
        id: '3',
        meeting_status: 'urgent',
        meetLink: 'https://meet.google.com/jkl-mno-pqr',
        meeting_date_time: new Date(2025, 9, 18, 9, 0).toISOString(), // Oct 18, 2025 9:00
        meeting_type: 'emergency_review',
        change_request: {
            requested_by: 'Client',
            request_type: 'time_change',
            request_status: 'pending',
            request_date_time: new Date().toISOString(),
        },
        date_time_updates: null,
        order: {
            id: 'order-3',
            name: 'Brand Identity',
        },
        cps: [
            {
                id: 'cp-1',
                name: 'John Designer',
                role: 'Design Lead',
                profile_picture: '',
            },
            {
                id: 'cp-4',
                name: 'Emily Artist',
                role: 'Graphic Designer',
                profile_picture: '',
            },
        ],
        createdAt: new Date().toISOString(),
        client: {
            id: 'client-3',
            name: 'Creative Studio',
            role: 'Creative Director',
            profile_picture: '',
        },
    },
];

// Status filter options
const statusFilters = [
    { id: 'all', label: 'All', color: 'bg-gray-500' },
    { id: 'holiday', label: 'Holiday', color: 'bg-blue-500' },
    { id: 'reminders', label: 'Reminders', color: 'bg-green-500' },
    { id: 'task', label: 'Task', color: 'bg-purple-500' },
    { id: 'urgent', label: 'Urgent', color: 'bg-red-500' },
];

function Index() {
    const [currentDate, setCurrentDate] = useState(new Date(2025, 9, 1)); // October 2025
    const [view, setView] = useState<'today' | 'week' | 'month'>('month');
    const [meetings, setEvents] = useState<Event[]>(staticEvents);
    const [selectedEvent, setSelectedEvent] = useState<Event | null>(null);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isAddEventModalOpen, setIsAddEventModalOpen] = useState(false);
    const [selectedStatus, setSelectedStatus] = useState<string>('all');
    const [selectedDate, setSelectedDate] = useState<Date>(new Date());
    const [addEventDate, setAddEventDate] = useState<Date>(new Date()); // For pre-filling the add event form

    const modalRef = useRef<HTMLDivElement>(null);

    // Generate mini calendar data
    const generateMiniCalendarData = () => {
        const year = currentDate.getFullYear();
        const month = currentDate.getMonth();
        const firstDay = new Date(year, month, 1);
        const lastDay = new Date(year, month + 1, 0);
        const daysInMonth = lastDay.getDate();

        const days = [];

        // Add previous month's trailing days
        const firstDayOfWeek = firstDay.getDay();
        const prevMonthLastDay = new Date(year, month, 0).getDate();
        for (let i = firstDayOfWeek - 1; i >= 0; i--) {
            days.push({
                date: new Date(year, month - 1, prevMonthLastDay - i),
                dayOfMonth: prevMonthLastDay - i,
                isCurrentMonth: false,
                meetings: [],
            });
        }

        // Add current month's days
        for (let i = 1; i <= daysInMonth; i++) {
            const date = new Date(year, month, i);
            days.push({
                date,
                dayOfMonth: i,
                isCurrentMonth: true,
                meetings: getEventsForDate(date),
            });
        }

        // Add next month's leading days
        const totalCells = 42; // 6 weeks
        const remainingDays = totalCells - days.length;
        for (let i = 1; i <= remainingDays; i++) {
            days.push({
                date: new Date(year, month + 1, i),
                dayOfMonth: i,
                isCurrentMonth: false,
                meetings: [],
            });
        }

        return days;
    };

    // Generate calendar data based on current view
    const generateCalendarData = () => {
        let startDate = new Date(currentDate);
        const days = [];

        if (view === 'today') {
            // Only show today
            days.push({
                date: new Date(currentDate),
                dayOfMonth: currentDate.getDate(),
                isCurrentMonth: true,
                meetings: getEventsForDate(currentDate),
            });
        } else if (view === 'week') {
            // Start from Monday of current week
            const day = currentDate.getDay();
            startDate.setDate(currentDate.getDate() - (day === 0 ? 6 : day - 1));

            // Generate 7 days (full week)
            for (let i = 0; i < 7; i++) {
                const date = new Date(startDate);
                date.setDate(date.getDate() + i);
                days.push({
                    date,
                    dayOfMonth: date.getDate(),
                    isCurrentMonth: date.getMonth() === currentDate.getMonth(),
                    meetings: getEventsForDate(date),
                });
            }
        } else if (view === 'month') {
            // Start from the first day of the month
            startDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
            // Adjust to the first Monday before or on the first day of the month
            const firstDayOfWeek = startDate.getDay();
            startDate.setDate(startDate.getDate() - (firstDayOfWeek === 0 ? 6 : firstDayOfWeek - 1));

            // Generate up to 42 days (6 weeks) to ensure we cover the full month
            for (let i = 0; i < 42; i++) {
                const date = new Date(startDate);
                date.setDate(date.getDate() + i);
                days.push({
                    date,
                    dayOfMonth: date.getDate(),
                    isCurrentMonth: date.getMonth() === currentDate.getMonth(),
                    meetings: getEventsForDate(date),
                });

                // Break if we've gone past the end of the month
                if (i > 28 && date.getMonth() !== currentDate.getMonth() && date.getDay() === 0) {
                    break;
                }
            }
        }

        return days;
    };

    // Get meetings for a specific date from the static data
    const getEventsForDate = (date: Date) => {
        const dateString = date.toISOString().split('T')[0];
        return meetings.filter((meeting) => {
            const meetingDate = new Date(meeting.meeting_date_time);
            return meetingDate.toISOString().split('T')[0] === dateString;
        });
    };

    const [calendarData, setCalendarData] = useState(generateCalendarData());
    const [miniCalendarData, setMiniCalendarData] = useState(generateMiniCalendarData());

    useEffect(() => {
        setCalendarData(generateCalendarData());
        setMiniCalendarData(generateMiniCalendarData());
    }, [currentDate, view, meetings]);

    const daysOfWeek = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'];
    const miniDaysOfWeek = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];

    // Handle date selection from mini calendar
    const handleMiniCalendarDateClick = (date: Date) => {
        setCurrentDate(date);
        setSelectedDate(date);

        // If in today view, switch to month view for better visibility
        if (view === 'today') {
            setView('month');
        }
    };

    // Handle date click in main calendar
    const handleMainCalendarDateClick = (date: Date) => {
        setSelectedDate(date);
        setAddEventDate(date);
        setIsAddEventModalOpen(true);
    };

    const navigatePrevious = () => {
        const newDate = new Date(currentDate);

        if (view === 'today') {
            newDate.setDate(currentDate.getDate() - 1);
        } else if (view === 'week') {
            newDate.setDate(currentDate.getDate() - 7);
        } else if (view === 'month') {
            newDate.setMonth(newDate.getMonth() - 1);
        }

        setCurrentDate(newDate);
        setSelectedDate(newDate);
    };

    const navigateNext = () => {
        const newDate = new Date(currentDate);

        if (view === 'today') {
            newDate.setDate(currentDate.getDate() + 1);
        } else if (view === 'week') {
            newDate.setDate(currentDate.getDate() + 7);
        } else if (view === 'month') {
            newDate.setMonth(newDate.getMonth() + 1);
        }

        setCurrentDate(newDate);
        setSelectedDate(newDate);
    };

    const goToToday = () => {
        const today = new Date();
        setCurrentDate(today);
        setSelectedDate(today);
    };

    const formatDateRange = () => {
        if (view === 'today') {
            return currentDate.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
        } else if (view === 'week') {
            const startOfWeek = new Date(calendarData[0]?.date);
            const endOfWeek = new Date(calendarData[calendarData.length - 1]?.date);

            if (startOfWeek && endOfWeek) {
                if (startOfWeek.getMonth() === endOfWeek.getMonth()) {
                    return `${startOfWeek.getDate()} - ${endOfWeek.getDate()} ${startOfWeek.toLocaleDateString('en-US', { month: 'long', year: 'numeric' })}`;
                } else {
                    return `${startOfWeek.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })} - ${endOfWeek.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}`;
                }
            }
            return '';
        } else {
            return currentDate.toLocaleDateString('en-US', { month: 'long', year: 'numeric' });
        }
    };

    // Format time for display
    const formatTime = (dateString: string) => {
        const date = new Date(dateString);
        return date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
    };

    // Handle meeting click to open modal
    const handleEventClick = (meeting: Event) => {
        setSelectedEvent(meeting);
        setIsModalOpen(true);
    };

    // Check if a date is the selected date
    const isSelectedDate = (date: Date) => {
        return date.toDateString() === selectedDate.toDateString();
    };

    return (
        <div className="flex h-full w-full flex-col bg-card">
            <Head title="Events" />
            <div className="border-b border-gray-200 bg-card">
                <GeneralHeader title="Events" description="Manage your events efficiently" page="Events" />
            </div>
            <div className="flex h-full flex-col gap-6 overflow-hidden p-2 lg:flex-row">
                {/* Left Sidebar - Mini Calendar & Filters */}
                <div className="sticky top-0 h-full space-y-6 overflow-y-auto lg:w-80">
                    {/* Add Event Button */}
                    <Button className="w-full bg-success" onClick={() => setIsAddEventModalOpen(true)}>
                        <Plus className="mr-2 h-4 w-4" />
                        Add Event
                    </Button>
                    {/* Mini Calendar */}
                    <Card className="p-2">
                        <CardHeader className="px-2 pb-3">
                            <div className="flex items-center justify-between">
                                <h3 className="font-semibold">{currentDate.toLocaleDateString('en-US', { month: 'long', year: 'numeric' })}</h3>
                                <div className="flex space-x-1">
                                    <div
                                        onClick={() => {
                                            const prevMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1);
                                            setCurrentDate(prevMonth);
                                        }}
                                        className="mr-5"
                                    >
                                        <ChevronLeft className="h-4 w-4" />
                                    </div>
                                    <div
                                        className=""
                                        onClick={() => {
                                            const nextMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1);
                                            setCurrentDate(nextMonth);
                                        }}
                                    >
                                        <ChevronRight className="h-4 w-4" />
                                    </div>
                                </div>
                            </div>
                        </CardHeader>
                        <CardContent className="px-0">
                            {/* Days of week header */}
                            <div className="mb-2 grid grid-cols-7 gap-1">
                                {miniDaysOfWeek.map((day) => (
                                    <div key={day} className="py-1 text-center text-xs font-medium text-gray-500">
                                        {day}
                                    </div>
                                ))}
                            </div>

                            {/* Calendar grid */}
                            <div className="grid grid-cols-7 gap-1">
                                {miniCalendarData.map((day, index) => (
                                    <button
                                        key={index}
                                        onClick={() => handleMiniCalendarDateClick(day.date)}
                                        className={`flex h-8 items-center justify-center rounded text-sm transition-colors ${
                                            !day.isCurrentMonth
                                                ? 'cursor-not-allowed text-gray-300'
                                                : isSelectedDate(day.date)
                                                  ? 'bg-success font-semibold text-white'
                                                  : day.date.toDateString() === new Date().toDateString()
                                                    ? 'bg-amber-100 font-semibold text-amber-800'
                                                    : 'cursor-pointer text-gray-700 hover:bg-gray-100'
                                        } ${day.meetings.length > 0 ? 'font-semibold' : ''}`}
                                        disabled={!day.isCurrentMonth}
                                    >
                                        {day.dayOfMonth}
                                    </button>
                                ))}
                            </div>
                        </CardContent>
                    </Card>

                    {/* Status Filters */}
                    <Card>
                        <CardHeader className="px-0 pb-3">
                            <div className="flex items-center justify-between">
                                <h3 className="flex items-center font-semibold">
                                    <Filter className="mr-2 h-4 w-4" />
                                    Status
                                </h3>
                            </div>
                        </CardHeader>
                        <CardContent className="space-y-3 px-0">
                            {statusFilters.map((status) => (
                                <div key={status.id} className="flex items-center space-x-2">
                                    <Checkbox
                                        id={status.id}
                                        checked={selectedStatus === status.id}
                                        onCheckedChange={() => setSelectedStatus(status.id)}
                                    />
                                    <Label htmlFor={status.id} className="flex cursor-pointer items-center space-x-2">
                                        <span className="font-medium">{status.label}</span>
                                    </Label>
                                </div>
                            ))}
                        </CardContent>
                    </Card>
                </div>

                {/* Main Calendar */}
                <div className="h-full flex-1 overflow-y-auto">
                    <Card className="w-full">
                        <CardHeader className="px-0 pb-3">
                            <div className="flex justify-between gap-4 sm:flex-row sm:items-center">
                                {/* <div className="flex space-x-1">
                                <Button
                                    variant={view === 'today' ? 'default' : 'outline'}
                                    size="sm"
                                    onClick={() => setView('today')}
                                    className={view === 'today' ? 'bg-success' : ''}
                                >
                                    Today
                                </Button>
                                <Button
                                    variant={view === 'week' ? 'default' : 'outline'}
                                    size="sm"
                                    onClick={() => setView('week')}
                                    className={view === 'week' ? 'bg-success' : ''}
                                >
                                    Week
                                </Button>
                                <Button
                                    variant={view === 'month' ? 'default' : 'outline'}
                                    size="sm"
                                    onClick={() => setView('month')}
                                    className={view === 'month' ? 'bg-success' : ''}
                                >
                                    Month
                                </Button>
                            </div> */}

                                <div className="flex items-center space-x-2">
                                    <div className="" onClick={navigatePrevious}>
                                        <ChevronLeft className="h-4 w-4" />
                                    </div>
                                    <span className="min-w-[150px] text-center text-sm font-medium">{formatDateRange()}</span>
                                    <div className="" onClick={navigateNext}>
                                        <ChevronRight className="h-4 w-4" />
                                    </div>
                                </div>

                                <Button size="sm" variant="outline" className="flex items-center space-x-1" onClick={goToToday}>
                                    <CalendarIcon className="h-4 w-4" />
                                    <span>Go Today</span>
                                </Button>
                            </div>
                        </CardHeader>

                        <CardContent className="p-0">
                            {/* Calendar Grid */}
                            <div className="overflow-auto rounded-b-xl border">
                                {view !== 'today' && (
                                    <div className={`grid ${view === 'week' ? 'grid-cols-7' : 'grid-cols-7'} border-b bg-gray-50/50`}>
                                        {daysOfWeek.map((day) => (
                                            <div key={day} className="border-r py-3 text-center text-sm font-medium text-gray-600 last:border-r-0">
                                                {day}
                                            </div>
                                        ))}
                                    </div>
                                )}

                                {/* Calendar Cells */}
                                <div className={`grid ${view === 'today' ? 'grid-cols-1' : view === 'week' ? 'grid-cols-7' : 'grid-cols-7'}`}>
                                    {calendarData.map((day, index) => (
                                        <div
                                            key={index}
                                            onClick={() => handleMainCalendarDateClick(day.date)}
                                            className={`min-h-[120px] cursor-pointer border-r border-b transition-colors last:border-r-0 hover:bg-gray-50 ${
                                                !day.isCurrentMonth ? 'bg-gray-50/30' : ''
                                            } ${
                                                isSelectedDate(day.date)
                                                    ? 'border-success bg-success/10'
                                                    : day.date.toDateString() === new Date().toDateString()
                                                      ? 'bg-amber-50'
                                                      : ''
                                            }`}
                                        >
                                            {/* Date Number */}
                                            <div className="p-2 text-sm text-gray-600">
                                                {view === 'month' && index < 7 && (
                                                    <span className="block text-xs text-gray-400 sm:hidden">{daysOfWeek[index]}</span>
                                                )}
                                                <span
                                                    className={`inline-flex h-6 w-6 items-center justify-center ${
                                                        isSelectedDate(day.date)
                                                            ? 'rounded-full bg-success font-semibold text-white'
                                                            : day.date.toDateString() === new Date().toDateString()
                                                              ? 'rounded-full bg-success text-white'
                                                              : ''
                                                    }`}
                                                >
                                                    {day.dayOfMonth}
                                                </span>
                                            </div>

                                            {/* Events */}
                                            <div className="space-y-1 px-1">
                                                {day.meetings.map((meeting, mIndex) => (
                                                    <div
                                                        key={mIndex}
                                                        className="flex cursor-pointer items-center justify-between rounded p-1.5 text-xs transition-colors hover:bg-gray-100"
                                                        onClick={(e) => {
                                                            e.stopPropagation(); // Prevent triggering the date click
                                                            handleEventClick(meeting);
                                                        }}
                                                    >
                                                        <div className="flex items-center truncate">
                                                            <div className="mr-2 flex -space-x-1">
                                                                {meeting.cps.slice(0, 3).map((cp, cpIndex) => (
                                                                    <Avatar key={cpIndex} className="h-5 w-5 border border-white">
                                                                        <AvatarImage src={cp.profile_picture} alt={cp.name} />
                                                                        <AvatarFallback className="bg-amber-200 text-xs text-amber-800">
                                                                            {cp.name.charAt(0).toUpperCase()}
                                                                        </AvatarFallback>
                                                                    </Avatar>
                                                                ))}
                                                            </div>
                                                            <span className="truncate font-medium">{meeting.order.name}</span>
                                                        </div>

                                                        <DropdownMenu>
                                                            <DropdownMenuTrigger asChild onClick={(e) => e.stopPropagation()}>
                                                                <Button variant="ghost" size="icon" className="h-6 w-6">
                                                                    <MoreHorizontal className="h-3 w-3" />
                                                                </Button>
                                                            </DropdownMenuTrigger>
                                                            <DropdownMenuContent align="end">
                                                                <DropdownMenuItem onClick={() => handleEventClick(meeting)}>
                                                                    View Details
                                                                </DropdownMenuItem>
                                                            </DropdownMenuContent>
                                                        </DropdownMenu>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                </div>

                {/* Event Details Modal */}
                <EventDetailsModal
                    isOpen={isModalOpen}
                    setIsOpen={setIsModalOpen}
                    selectedEvent={selectedEvent}
                    formatTime={formatTime}
                    modalRef={modalRef}
                />

                {/* Add Event Modal */}
                <AddEventModal
                    isOpen={isAddEventModalOpen}
                    setIsOpen={setIsAddEventModalOpen}
                    addEventDate={addEventDate}
                    onSubmit={(eventData) => {
                        // Handle the event submission here
                        console.log('Event submitted:', eventData);
                    }}
                />
            </div>
        </div>
    );
}
Index.layout = (page: ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Tasks', href: '/tasks' },
            { title: 'Tasks', href: route('users.index') },
        ]}
        title="Tasks"
    >
        {page}
    </AppLayout>
);

export default Index;
