// src/components/calendar/EventItem.tsx
import React from 'react';
import { View, StyleSheet, TouchableOpacity } from 'react-native';
import { Text, useTheme } from 'react-native-paper';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { format, parseISO, isValid } from 'date-fns';

import { CalendarEvent } from '../../types/calendar';
import { AppStackParamList } from '../../navigation/AppNavigator'; // Adjust path if needed

interface EventItemProps {
    event: CalendarEvent;
    showTime?: boolean; // Optional prop to show time
}

// Define navigation prop type for navigating to EventForm
type EventItemNavigationProp = StackNavigationProp<AppStackParamList, 'EventForm'>;

const EventItem: React.FC<EventItemProps> = ({ event, showTime = true }) => {
    const theme = useTheme();
    const navigation = useNavigation<EventItemNavigationProp>();

    if (!event || typeof event.start !== 'string') {
        return null; // Don't render if event or start date is invalid
    }

    const startDate = parseISO(event.start);
    if (!isValid(startDate)) {
        return null; // Don't render if start date is invalid
    }

    const eventColor = event.color || theme.colors.primary;

    const styles = StyleSheet.create({
        container: {
            backgroundColor: eventColor,
            borderRadius: 4,
            paddingVertical: 2,
            paddingHorizontal: 4,
            marginBottom: 2, // Space between event items
            overflow: 'hidden',
        },
        text: {
            color: theme.colors.onPrimary, // Ensure text is readable on the background color
            fontSize: 10,
            fontWeight: 'bold',
        },
        timeText: {
            fontSize: 8,
            fontWeight: 'normal',
            color: theme.colors.onPrimary,
            marginRight: 2, // Space between time and title
        },
        tagContainer: {
            flexDirection: 'row',
            flexWrap: 'wrap',
            marginTop: 1,
        },
        tag: {
            backgroundColor: 'rgba(255, 255, 255, 0.3)', // Semi-transparent white
            borderRadius: 3,
            paddingHorizontal: 3,
            paddingVertical: 1,
            marginRight: 2,
            marginBottom: 1,
        },
        tagText: {
            color: theme.colors.onPrimary,
            fontSize: 8,
        },
    });

    const handlePress = () => {
        navigation.navigate('EventForm', { eventId: event.id });
    };

    // Determine if time should be shown: only if showTime is true AND the event is NOT all_day
    const shouldDisplayTime = showTime && !event.all_day;
    const timeString = shouldDisplayTime ? format(startDate, 'p') : ''; // Format time like 1:00 PM

    return (
        <TouchableOpacity onPress={handlePress} style={styles.container}>
            <Text style={styles.text} numberOfLines={2} ellipsizeMode='clip'>
                {/* Conditionally render time based on shouldDisplayTime */}
                {shouldDisplayTime && <Text style={styles.timeText}>{timeString} </Text>}
                {event.title}
            </Text>
            {/* Optional: Display tags if they exist */}
            {event.tags && event.tags.length > 0 && (
                <View style={styles.tagContainer}>
                    {event.tags.map((tag, index) => (
                        <View key={index} style={styles.tag}>
                            <Text style={styles.tagText}>{tag}</Text>
                        </View>
                    ))}
                </View>
            )}
        </TouchableOpacity>
    );
};

export default React.memo(EventItem); // Memoize for performance
