// src/components/calendar/WeekView.tsx
import React, { useMemo } from 'react';
import { View, StyleSheet, ScrollView } from 'react-native'; // Removed Dimensions unless used elsewhere
import { Text, useTheme } from 'react-native-paper';
import { eachDayOfInterval, format, isToday } from 'date-fns';

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

interface WeekViewProps {
    startDate: Date; // Start of the week
    endDate: Date; // End of the week
    eventsByDate: { [key: string]: CalendarEvent[] };
}

// Define size here, consistent with other views
const dateNumberSize = 24;

const WeekView: React.FC<WeekViewProps> = ({ startDate, endDate, eventsByDate }) => {
    const theme = useTheme();
    const days = useMemo(() => eachDayOfInterval({ start: startDate, end: endDate }), [
        startDate,
        endDate,
    ]);

    // Define standard week day names - ensure order matches your locale/calendar needs
    // const weekDays = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']; // Static names
    // Or generate dynamically from the days array to be safer
    const weekDays = days.map(day => format(day, 'EEE').toUpperCase());

    // --- Define styles inside the component to access theme ---
    const styles = StyleSheet.create({
        container: {
            flex: 1,
        },
        headerRow: {
            flexDirection: 'row',
            paddingVertical: 5,
            paddingBottom: 0,
            backgroundColor: theme.colors.background,
        },
        headerCell: {
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
            borderLeftWidth: 0.5,
            borderRightWidth: 0.5,
            borderColor: theme.colors.outlineVariant,
            backgroundColor: theme.colors.background,
        },
        headerText: {
            fontSize: 11,
            fontWeight: 'bold',
            color: theme.colors.onSurfaceVariant,
        },
        contentRow: {
            flex: 1,
            flexDirection: 'row',
        },
        dayColumn: {
            flex: 1,
            borderWidth: 0.5,
            borderTopWidth: 0,
            borderColor: theme.colors.outlineVariant,
            padding: 2,
            paddingTop: 0, // Keep this 0 if header handles top padding
            backgroundColor: theme.colors.background,
            overflow: 'hidden',
        },
        dayHeader: { // Consistent name
            alignItems: 'center',
            justifyContent: 'center',
            marginBottom: 2,
            // Use minHeight for consistency
            minHeight: dateNumberSize + 4,
        },
        dateNumberContainer: { // Base container for the date number
            width: dateNumberSize,
            height: dateNumberSize,
            alignItems: 'center',
            justifyContent: 'center',
        },
        todayCircle: { // Style for the *filled* circle highlight
            backgroundColor: theme.colors.primary,
            borderRadius: dateNumberSize / 2,
        },
        dateNumber: { // Base style for the date number text
            fontSize: 12,
            color: theme.colors.onSurface, // Default text color
            textAlign: 'center',
            padding: 0,
            includeFontPadding: false,
            fontWeight: 'normal', // Base weight
        },
        todayDateNumber: { // Specific style for text on today's date
             color: theme.colors.onPrimary, // Contrast with primary background
             fontWeight: 'bold', // Make today bold
        },
        eventsContainer: {
            flex: 1,
            padding: 2,
        },
    });
     // --- End of styles ---

    return (
        <View style={styles.container}>
            <View style={styles.headerRow}>
                {weekDays.map((dayName, index) => ( // Use generated weekdays map
                    <View key={`${dayName}-${index}`} style={styles.headerCell}>
                        <Text style={styles.headerText}>{dayName}</Text>
                    </View>
                ))}
            </View>
            <View style={styles.contentRow}>
                {days.map((day) => { // Removed unused index
                    const dateKey = format(day, 'yyyy-MM-dd');
                    const dayEvents = eventsByDate[dateKey] || [];
                    const today = isToday(day);

                    // Removed inline dateNumberStyle object creation

                    return (
                        <View key={dateKey} style={{ flex: 1 }}>
                            <View style={styles.dayColumn}>
                                <View style={styles.dayHeader}>
                                    {/* Apply base container style, and add circle style conditionally */}
                                    <View style={[
                                        styles.dateNumberContainer, // Base size and alignment
                                        today && styles.todayCircle  // Conditional circle background
                                    ]}>
                                        <Text style={[
                                            styles.dateNumber, // Base text style
                                            today && styles.todayDateNumber // Conditional color/weight override
                                        ]}>
                                            {format(day, 'd')}
                                        </Text>
                                    </View>
                                </View>
                                <ScrollView style={styles.eventsContainer} nestedScrollEnabled={true}>
                                    {dayEvents.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
                                        .map(event => (
                                            <EventItem key={event.id} event={event} showTime={true} /> // Show time in week view
                                        ))}
                                </ScrollView>
                            </View>
                        </View>
                    );
                })}
            </View>
        </View>
    );
};

export default WeekView;