/**
 * Calendar View Component
 * 
 * Displays content plan items as calendar events using react-big-calendar
 */

import React, { useMemo, useState, useCallback } from '@wordpress/element';
import { Calendar, dateFnsLocalizer, View, SlotInfo } from 'react-big-calendar';
import format from 'date-fns/format';
import parse from 'date-fns/parse';
import startOfWeek from 'date-fns/startOfWeek';
import getDay from 'date-fns/getDay';
import enUS from 'date-fns/locale/en-US';
import 'react-big-calendar/lib/css/react-big-calendar.css';
import { useContentPlan } from '../context/ContentPlanContext';
import { ContentPlanItem } from '../types';

// Create localizer using date-fns
const locales = {
    'en-US': enUS,
};

const localizer = dateFnsLocalizer({
    format,
    parse,
    startOfWeek,
    getDay,
    locales,
});

interface CalendarEvent {
    id: number;
    title: string;
    start: Date;
    end: Date;
    resource: ContentPlanItem;
}

interface CalendarViewProps {
    getString: (category: string, key: string, fallback?: string) => string;
}

const CalendarView: React.FC<CalendarViewProps> = ({ getString }) => {
    const {
        contentPlan,
        openSidebar,
    } = useContentPlan();

    const [currentView, setCurrentView] = useState<View>('month');
    const [currentDate, setCurrentDate] = useState<Date>(new Date());

    // Convert content plan items to calendar events
    const events: CalendarEvent[] = useMemo(() => {
        return contentPlan.contentPlanItems
            .filter(item => item.scheduled_on) // Only include items with scheduled dates
            .map(item => {
                const scheduledDate = new Date(item.scheduled_on!);
                // Set time to start of day for better calendar display
                const start = new Date(scheduledDate);
                start.setHours(0, 0, 0, 0);
                
                // End date is same day, end of day
                const end = new Date(scheduledDate);
                end.setHours(23, 59, 59, 999);

                return {
                    id: item.id,
                    title: item.title || getString('table_cells', 'untitled', 'Untitled'),
                    start,
                    end,
                    resource: item,
                };
            });
    }, [contentPlan.contentPlanItems, getString]);

    // Handle event selection
    const handleSelectEvent = useCallback((event: CalendarEvent) => {
        // Dispatch event to ContentPlanItemSidebar with the item data (same pattern as ContentPlanTable)
        window.dispatchEvent(
            new CustomEvent('editContentPlanItem', {
                detail: { item: event.resource },
            })
        );
        openSidebar('content-plan-item');
    }, [openSidebar]);

    // Handle date selection (for creating new items)
    const handleSelectSlot = useCallback((_slotInfo: SlotInfo) => {
        // Could open a modal to create a new item at this date
    }, []);

    // Get event style - all events use the same color
    const eventStyleGetter = useCallback((event: CalendarEvent) => {
        const backgroundColor = '#3174ad'; // Default blue
        const borderColor = '#3174ad';

        return {
            style: {
                backgroundColor,
                borderColor,
                color: '#fff',
                borderRadius: '4px',
                border: 'none',
                padding: '2px 4px',
                fontSize: '0.875rem',
            },
        };
    }, []);

    return (
        <div className="calendar-view-container" style={{ height: '600px' }}>
            <Calendar
                localizer={localizer}
                events={events}
                startAccessor="start"
                endAccessor="end"
                style={{ height: '100%' }}
                view={currentView}
                date={currentDate}
                onView={setCurrentView}
                onNavigate={setCurrentDate}
                onSelectEvent={handleSelectEvent}
                onSelectSlot={handleSelectSlot}
                selectable
                eventPropGetter={eventStyleGetter}
                popup
                views={['month']}
                messages={{
                    next: getString('common', 'next', 'Next'),
                    previous: getString('common', 'previous', 'Previous'),
                    today: getString('common', 'today', 'Today'),
                    month: getString('common', 'month', 'Month'),
                    week: getString('common', 'week', 'Week'),
                    day: getString('common', 'day', 'Day'),
                    agenda: getString('common', 'agenda', 'Agenda'),
                    date: getString('common', 'date', 'Date'),
                    time: getString('common', 'time', 'Time'),
                    event: getString('common', 'event', 'Event'),
                    noEventsInRange: getString('common', 'no_events_in_range', 'No events in this range'),
                }}
            />
        </div>
    );
};

export default CalendarView;
