// src/components/calendar/MonthView.tsx
import React, { useMemo } from 'react';
import { View, StyleSheet, Dimensions } from 'react-native';
import { Text, useTheme } from 'react-native-paper';
import {
    eachDayOfInterval, endOfMonth, startOfMonth, format, getDay, isSameMonth,
    startOfWeek, endOfWeek, addDays
} from 'date-fns';

import CalendarDayCell from './CalendarDayCell';
import { CalendarEvent } from '../../types/calendar';

interface MonthViewProps {
    startDate: Date; // Should be the start of the month
    endDate: Date; // Should be the end of the month
    eventsByDate: { [key: string]: CalendarEvent[] };
}

const screenWidth = Dimensions.get('window').width;
const cellWidth = screenWidth / 7; // Approximate width for each day cell

const MonthView: React.FC<MonthViewProps> = ({ startDate, eventsByDate }) => {
    const theme = useTheme();
    const currentMonth = startDate; // The month being displayed

    // Calculate the full range of days to display, including leading/trailing days from other months
    const monthStart = startOfMonth(currentMonth);
    const monthEnd = endOfMonth(currentMonth);
    const displayStart = startOfWeek(monthStart, { weekStartsOn: 1 }); // Week starts Monday
    const displayEnd = endOfWeek(monthEnd, { weekStartsOn: 1 });

    const days = useMemo(() => eachDayOfInterval({ start: displayStart, end: displayEnd }), [
        displayStart,
        displayEnd,
    ]);

    // Generate week rows
    const weeks: Date[][] = [];
    let currentWeek: Date[] = [];
    days.forEach((day, index) => {
        currentWeek.push(day);
        if ((index + 1) % 7 === 0) {
            weeks.push(currentWeek);
            currentWeek = [];
        }
    });

    const weekDays = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'];

    const styles = StyleSheet.create({
        container: { flex: 1 },
        weekRow: {
            flexDirection: 'row',
            flex: 1,
        },
        dayHeaderRow: {
            flexDirection: 'row',
            paddingVertical: 5,
            paddingBottom: 0,
            backgroundColor: theme.colors.background,
        },
        dayHeaderCell: {
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
            borderLeftWidth: 0.5,
            borderRightWidth: 0.5,
            borderColor: theme.colors.outlineVariant,
            backgroundColor: theme.colors.background,
        },
        dayHeaderText: {
            fontSize: 11,
            fontWeight: 'bold',
            color: theme.colors.onSurfaceVariant,
        },
    });

    return (
        <View style={styles.container}>
            <View style={styles.dayHeaderRow}>
                {weekDays.map(day => (
                    <View key={day} style={styles.dayHeaderCell}>
                        <Text style={styles.dayHeaderText}>{day}</Text>
                    </View>
                ))}
            </View>
            {weeks.map((week, weekIndex) => (
                <View key={`week-${weekIndex}`} style={styles.weekRow}>
                    {week.map(day => {
                        const dateKey = format(day, 'yyyy-MM-dd');
                        const dayEvents = eventsByDate[dateKey] || [];
                        return (
                            <CalendarDayCell
                                key={dateKey}
                                date={day}
                                events={dayEvents}
                                isCurrentMonth={isSameMonth(day, currentMonth)}
                            />
                        );
                    })}
                </View>
            ))}
        </View>
    );
};

export default MonthView;
