'use client';

import { useState, useEffect } from 'react';
import { ChevronLeft, ChevronRight, Plus, Calendar as CalendarIcon } from 'lucide-react';
import { EventWithTags } from '@/types/tags';
import EventForm from '../../../components/events/EventForm';

interface InteractiveCalendarProps {
    className?: string;
}

export function InteractiveCalendar({ className = '' }: InteractiveCalendarProps) {
    const [currentDate, setCurrentDate] = useState(new Date());
    const [selectedDate, setSelectedDate] = useState<Date | null>(null);
    const [events, setEvents] = useState<EventWithTags[]>([]);
    const [showEventModal, setShowEventModal] = useState(false);
    const [loading, setLoading] = useState(false);

    // חישוב תאריכים לחודש הנוכחי
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth();

    const firstDayOfMonth = new Date(year, month, 1);
    const lastDayOfMonth = new Date(year, month + 1, 0);
    const firstDayOfWeek = firstDayOfMonth.getDay();
    const daysInMonth = lastDayOfMonth.getDate();

    // ימי השבוע בעברית
    const weekDays = ['א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ש'];

    // יצירת מערך ימים לתצוגה
    const days = [];

    // ימים מהחודש הקודם
    const prevMonth = new Date(year, month - 1, 0);
    for (let i = firstDayOfWeek - 1; i >= 0; i--) {
        days.push({
            date: new Date(year, month - 1, prevMonth.getDate() - i),
            isCurrentMonth: false,
            isToday: false
        });
    }

    // ימי החודש הנוכחי
    const today = new Date();
    for (let day = 1; day <= daysInMonth; day++) {
        const date = new Date(year, month, day);
        days.push({
            date,
            isCurrentMonth: true,
            isToday: date.toDateString() === today.toDateString()
        });
    }

    // ימים מהחודש הבא
    const remainingDays = 42 - days.length; // 6 שבועות * 7 ימים
    for (let day = 1; day <= remainingDays; day++) {
        days.push({
            date: new Date(year, month + 1, day),
            isCurrentMonth: false,
            isToday: false
        });
    }

    // טעינת אירועים
    useEffect(() => {
        loadEvents();
    }, [currentDate]);

    const loadEvents = async () => {
        setLoading(true);
        try {
            const startDate = new Date(year, month, 1);
            const endDate = new Date(year, month + 1, 0);

            // תיקון תאריכים - הוספת יום אחד לתאריך הסיום
            endDate.setDate(endDate.getDate() + 1);

            const response = await fetch(`/api/calendar?start_date=${startDate.toISOString()}&end_date=${endDate.toISOString()}`);
            if (response.ok) {
                const data = await response.json();
                setEvents(data.events || []);
            }
        } catch (error) {
            console.error('Error loading events:', error);
        } finally {
            setLoading(false);
        }
    };

    // קבלת אירועים לתאריך מסוים
    const getEventsForDate = (date: Date) => {
        return events.filter(event => {
            const eventDate = new Date(event.start_datetime);
            return eventDate.toDateString() === date.toDateString();
        });
    };

    // ניווט בין חודשים
    const goToPreviousMonth = () => {
        setCurrentDate(new Date(year, month - 1));
    };

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

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

    // לחיצה על תאריך
    const handleDateClick = (date: Date) => {
        setSelectedDate(date);
        setShowEventModal(true);
    };

    // Handle event click
    const handleEventClick = (event: EventWithTags, e: React.MouseEvent) => {
        e.stopPropagation(); // Prevent date click
        // Navigate to event details page
        window.location.href = `/events/${event.id}`;
    };

    // סגירת מודאל
    const handleCloseModal = async () => {
        setShowEventModal(false);
        setSelectedDate(null);
        // המתנה קצרה כדי לוודא שהאירוע נשמר במסד הנתונים
        await new Promise(resolve => setTimeout(resolve, 100));
        await loadEvents(); // רענון האירועים
    };

    // עיצוב תאריך
    const formatDate = (date: Date) => {
        return new Intl.DateTimeFormat('he-IL', {
            year: 'numeric',
            month: 'long'
        }).format(date);
    };

    return (
        <div className={`bg-white rounded-lg shadow ${className}`}>
            {/* כותרת לוח השנה */}
            <div className="flex items-center justify-between p-4 border-b">
                <h2 className="text-xl font-semibold text-gray-900 flex items-center gap-2">
                    <CalendarIcon className="w-6 h-6" />
                    לוח אירועים
                </h2>
                <div className="flex items-center gap-2">
                    <button
                        onClick={goToToday}
                        className="px-3 py-1 text-sm bg-blue-100 text-blue-700 rounded-md hover:bg-blue-200"
                    >
                        היום
                    </button>
                    <button
                        onClick={goToPreviousMonth}
                        className="p-1 hover:bg-gray-100 rounded"
                        aria-label="חודש קודם"
                    >
                        <ChevronLeft className="w-5 h-5" />
                    </button>
                    <button
                        onClick={goToNextMonth}
                        className="p-1 hover:bg-gray-100 rounded"
                        aria-label="חודש הבא"
                    >
                        <ChevronRight className="w-5 h-5" />
                    </button>
                </div>
            </div>

            {/* שם החודש */}
            <div className="text-center py-4">
                <h3 className="text-lg font-medium text-gray-900">
                    {formatDate(currentDate)}
                </h3>
            </div>

            {/* לוח השנה */}
            <div className="p-4">
                {/* ימי השבוע */}
                <div className="grid grid-cols-7 gap-1 mb-2">
                    {weekDays.map(day => (
                        <div key={day} className="text-center text-sm font-medium text-gray-500 py-2">
                            {day}
                        </div>
                    ))}
                </div>

                {/* ימי החודש */}
                <div className="grid grid-cols-7 gap-1">
                    {days.map((day, index) => {
                        const dayEvents = getEventsForDate(day.date);
                        const isSelected = selectedDate && day.date.toDateString() === selectedDate.toDateString();

                        return (
                            <div
                                key={index}
                                className={`
                                    min-h-[80px] p-1 border border-gray-200 cursor-pointer hover:bg-gray-50
                                    ${day.isCurrentMonth ? 'bg-white' : 'bg-gray-50 text-gray-400'}
                                    ${day.isToday ? 'bg-blue-50 border-blue-300' : ''}
                                    ${isSelected ? 'bg-blue-100 border-blue-400' : ''}
                                `}
                                onClick={() => handleDateClick(day.date)}
                            >
                                <div className="text-sm font-medium mb-1">
                                    {day.date.getDate()}
                                </div>

                                {/* אירועים */}
                                <div className="space-y-1">
                                    {dayEvents.slice(0, 3).map(event => (
                                        <div
                                            key={event.id}
                                            className="text-xs p-1 rounded truncate cursor-pointer hover:opacity-80 transition-opacity"
                                            style={{
                                                backgroundColor: event.tags?.[0]?.color || '#3B82F6',
                                                color: 'white'
                                            }}
                                            onClick={(e) => handleEventClick(event, e)}
                                            title={`לחץ לצפייה בפרטי האירוע: ${event.title}`}
                                        >
                                            {event.title}
                                        </div>
                                    ))}
                                    {dayEvents.length > 3 && (
                                        <div className="text-xs text-gray-500">
                                            +{dayEvents.length - 3} נוספים
                                        </div>
                                    )}
                                </div>
                            </div>
                        );
                    })}
                </div>
            </div>

            {/* מודאל הוספת אירוע */}
            {showEventModal && selectedDate && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
                    <div className="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
                        <div className="p-4 border-b">
                            <div className="flex items-center justify-between">
                                <h3 className="text-lg font-semibold">
                                    הוסף אירוע - {selectedDate.toLocaleDateString('he-IL')}
                                </h3>
                                <button
                                    onClick={handleCloseModal}
                                    className="text-gray-400 hover:text-gray-600"
                                >
                                    ×
                                </button>
                            </div>
                        </div>
                        <div className="p-4">
                            <EventForm
                                mode="create"
                                defaultStartDatetime={`${selectedDate.getFullYear()}-${String(selectedDate.getMonth() + 1).padStart(2, '0')}-${String(selectedDate.getDate()).padStart(2, '0')}T10:00`}
                                onSuccess={handleCloseModal}
                            />
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
