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

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

interface ThreeDayViewProps {
    startDate: Date; // Start of the 3-day period
    endDate: Date; // End of the 3-day period
    eventsByDate: { [key: string]: CalendarEvent[] };
}

// Get screen width
// const screenWidth = Dimensions.get('window').width; // No longer needed here if dayColumn uses flex:1
// const dayColumnWidth = screenWidth / 3;
const dateNumberSize = 24; // Define a size for the circle/text container

const ThreeDayView: React.FC<ThreeDayViewProps> = ({ startDate, endDate, eventsByDate }) => {
    const theme = useTheme();
    // Ensure endDate is included in the interval
    const days = useMemo(() => eachDayOfInterval({ start: startDate, end: endDate }), [
        startDate,
        endDate,
    ]);

    // Ensure exactly 3 days are generated if interval logic is tricky
    const displayDays = days.slice(0, 3);

    // Get abbreviated day names for the displayed days
    const weekDays = displayDays.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: {
            alignItems: 'center',
            justifyContent: 'center',
            marginBottom: 2,
            minHeight: dateNumberSize + 4, // Slightly larger than circle to give space
        },
        // Base container for the date number - useful for alignment consistency
        dateNumberContainer: {
            width: dateNumberSize,
            height: dateNumberSize,
            alignItems: 'center',
            justifyContent: 'center',
            // Removed borderRadius and background/border from here
        },
        todayCircle: {
            backgroundColor: theme.colors.primary, // Use background for filled circle
            borderRadius: dateNumberSize / 2,      // Make it circular
        },
        dateNumber: {
            fontSize: 12,
            color: theme.colors.onSurface,
            textAlign: 'center', // Keep textAlign, helps sometimes
            padding: 0,          // Ensure no padding interferes
            includeFontPadding: false, // Keep this
            // Removed width property
        },
        todayDateNumber: { // Specific style for text color on today's date
            color: theme.colors.onPrimary, // Color that contrasts with primary background
            fontWeight: 'bold',
        },
        eventsContainer: {
            flex: 1,
            padding: 2,
        },
    });
    // --- End of styles ---


    return (
        <View style={styles.container}>
            <View style={styles.headerRow}>
                {weekDays.map((dayName, index) => (
                    <View key={dayName + index} style={styles.headerCell}>
                        <Text style={styles.headerText}>{dayName}</Text>
                    </View>
                ))}
            </View>
            <View style={styles.contentRow}>
                {displayDays.map((day) => { // Removed index as it wasn't used after checks removed
                    const dateKey = format(day, 'yyyy-MM-dd');
                    const dayEvents = eventsByDate[dateKey] || [];
                    const today = isToday(day);

                    return (
                        // Use flex: 1 container for each day column
                        <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 for today
                                        ]}>
                                            {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} />
                                        ))}
                                </ScrollView>
                            </View>
                        </View>
                    );
                })}
            </View>
        </View>
    );
};

export default ThreeDayView;