import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { ChevronLeft, ChevronRight } from 'lucide-react-native';
import { TimeOffRequest, TimeOffRequestType } from '@/types/types';

interface CalendarWidgetProps {
    events: TimeOffRequest[];
    types: TimeOffRequestType[];
    onMonthChange?: (date: Date) => void;
}

export default function CalendarWidget({ events, types, onMonthChange }: CalendarWidgetProps) {
    const [currentDate, setCurrentDate] = useState(new Date());

    // Calendar helpers
    const daysInMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0).getDate();
    const firstDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1).getDay(); // 0 = Sun
    const adjustedFirstDay = firstDayOfMonth === 0 ? 6 : firstDayOfMonth - 1; // 0 = Mon

    const weekDays = ['Lun', 'Mar', 'Mer', 'Gio', 'Ven', 'Sab', 'Dom'];

    const changeMonth = (increment: number) => {
        const newDate = new Date(currentDate.setMonth(currentDate.getMonth() + increment));
        setCurrentDate(new Date(newDate));
        if (onMonthChange) {
            onMonthChange(newDate);
        }
    };

    useEffect(() => {
        if (onMonthChange) {
            onMonthChange(currentDate);
        }
    }, []);

    const getEventForDay = (day: number) => {
        const year = currentDate.getFullYear();
        const month = String(currentDate.getMonth() + 1).padStart(2, '0');
        const dayStr = String(day).padStart(2, '0');
        const dateStr = `${year}-${month}-${dayStr}`;

        return events.find(event => {
            // Simple logic: check if the date falls within the range
            // Note: for perfect logic on long ranges, a more thorough check would be needed
            if (!event.start_date) return false;
            if (event.timeOffRequestType.name === 'Permesso') return event.start_date === dateStr;
            const end = event.end_date || event.start_date;
            return dateStr >= event.start_date && dateStr <= end;
        });
    };

    return (
        <View className="bg-white rounded-[2rem] p-6 shadow-sm border border-gray-100">
            {/* Month Header */}
            <View className="flex-row justify-between items-center mb-6">
                <TouchableOpacity
                    onPress={() => changeMonth(-1)}
                    className="p-2 bg-gray-50 rounded-full"
                >
                    <ChevronLeft size={24} color="#374151" />
                </TouchableOpacity>
                <Text className="text-xl font-bold text-gray-800 capitalize">
                    {currentDate.toLocaleString('it-IT', { month: 'long', year: 'numeric' })}
                </Text>
                <TouchableOpacity
                    onPress={() => changeMonth(1)}
                    className="p-2 bg-gray-50 rounded-full"
                >
                    <ChevronRight size={24} color="#374151" />
                </TouchableOpacity>
            </View>

            {/* Week Header */}
            <View className="flex-row justify-between mb-4">
                {weekDays.map(day => (
                    <Text key={day} className="w-10 text-center text-xs font-bold text-gray-400 uppercase">{day}</Text>
                ))}
            </View>

            {/* Days Grid */}
            <View className="flex-row flex-wrap gap-y-4">
                {/* Empty slots for alignment */}
                {Array.from({ length: adjustedFirstDay }).map((_, i) => (
                    <View key={`empty-${i}`} style={{ width: '14.28%' }} />
                ))}
                {/* Days */}
                {Array.from({ length: daysInMonth }).map((_, i) => {
                    const day = i + 1;
                    const event = getEventForDay(day);

                    let bgClass = 'bg-transparent';
                    let textClass = 'text-gray-700';
                    let borderClass = 'border-transparent';

                    const bgColor = event?.timeOffRequestType?.color ? `${event.timeOffRequestType.color}25` : 'transparent';
                    const borderColor = event?.timeOffRequestType?.color || 'transparent';
                    const textColor = event ? event.timeOffRequestType?.color : '#374151';

                    return (
                        <View key={day} style={{ width: '14.28%' }} className="items-center">
                            <View className={`w-10 h-10 rounded-full items-center justify-center border`} style={{backgroundColor: bgColor, borderColor: borderColor }}>
                                <Text className={`text-sm ${event ? 'font-bold' : ''}`} style={{ color: textColor }}>{day}</Text>
                            </View>
                        </View>
                    );
                })}
            </View>

            {/* Legend */}
            <View className="flex-row flex-wrap justify-center gap-4 mt-8 pt-4 border-t border-gray-100">
                {types.map((type) => (
                    <View key={type.id} className="flex-row items-center" >
                        <View className={`w-3 h-3 rounded-full mr-2`} style={{ backgroundColor: type.color }} />
                        <Text className="text-sm font-medium text-gray-500">{type.name}</Text>
                    </View>
                ))} 
            </View>
        </View>
    );
}