import { Head, Link, usePage } from '@inertiajs/react';
import { useMemo } from 'react';
import '../../../css/schedule.css';

type ScheduleItem = {
    id: string;
    eventId: string;
    eventTitle: string;
    title: string;
    description: string | null;
    startsAt: string;
    endsAt: string | null;
    location: string | null;
    isPublished: boolean;
    updatedAt?: string;
};

type IndexPageProps = { wedding: { name: string; timezone: string }; items: ScheduleItem[] };

const dateKey = (value: string, timeZone: string) => {
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return 'unknown';
    try {
        const parts = new Intl.DateTimeFormat('en-CA', { timeZone, year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(date);
        const part = (type: Intl.DateTimeFormatPartTypes) => parts.find((entry) => entry.type === type)?.value ?? '';
        return `${part('year')}-${part('month')}-${part('day')}`;
    } catch {
        return date.toISOString().slice(0, 10);
    }
};

const formatDay = (value: string, timeZone: string) => {
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return 'Datum nicht verfügbar';
    try {
        return new Intl.DateTimeFormat('de-DE', { timeZone, weekday: 'long', day: '2-digit', month: 'long', year: 'numeric' }).format(date);
    } catch {
        return new Intl.DateTimeFormat('de-DE', { dateStyle: 'full' }).format(date);
    }
};

const formatTime = (value: string, timeZone: string) => {
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return '--:--';
    try {
        return new Intl.DateTimeFormat('de-DE', { timeZone, hour: '2-digit', minute: '2-digit' }).format(date);
    } catch {
        return new Intl.DateTimeFormat('de-DE', { timeStyle: 'short' }).format(date);
    }
};

export default function ScheduleIndex() {
    const { wedding, items } = usePage<IndexPageProps>().props;
    const now = Date.now();
    const publishedItems = useMemo(() => [...items]
        .filter((item) => item.isPublished)
        .sort((left, right) => new Date(left.startsAt).getTime() - new Date(right.startsAt).getTime()), [items]);
    const highlightedId = publishedItems.find((item) => {
        const start = new Date(item.startsAt).getTime();
        const end = item.endsAt ? new Date(item.endsAt).getTime() : start;
        return start <= now && now <= end;
    })?.id ?? publishedItems.find((item) => new Date(item.startsAt).getTime() >= now)?.id ?? null;
    const groups = useMemo(() => {
        const result = new Map<string, ScheduleItem[]>();
        publishedItems.forEach((item) => {
            const key = dateKey(item.startsAt, wedding.timezone);
            result.set(key, [...(result.get(key) ?? []), item]);
        });
        return [...result.entries()];
    }, [publishedItems, wedding.timezone]);

    return (
        <>
            <Head title="Ablauf" />
            <main className="schedule-index-shell">
                <nav className="schedule-nav" aria-label="Bereichsnavigation"><div><span className="schedule-eyebrow">{wedding.name}</span><strong>Ablauf</strong></div><Link className="schedule-secondary-button" href="/dashboard">Zurück zum Dashboard</Link></nav>
                <header className="schedule-index-header"><span className="schedule-eyebrow">Euer Zeitplan</span><h1>Gemeinsam durch den Tag</h1><p>Hier findet ihr alle veröffentlichten Programmpunkte der Veranstaltungen, zu denen ihr eingeladen seid.</p></header>
                {publishedItems.length === 0 ? <section className="schedule-index-empty"><span aria-hidden="true">◇</span><h2>Noch kein Ablauf veröffentlicht</h2><p>Sobald Programmpunkte für euch bereitstehen, erscheinen sie an dieser Stelle.</p></section> : <div className="schedule-timeline">{groups.map(([key, dayItems]) => <section className="schedule-day" aria-labelledby={`schedule-day-${key}`} key={key}><header><span aria-hidden="true">◇</span><h2 id={`schedule-day-${key}`}>{formatDay(dayItems[0].startsAt, wedding.timezone)}</h2></header><ol>{dayItems.map((item) => { const starts = new Date(item.startsAt).getTime(); const ends = item.endsAt ? new Date(item.endsAt).getTime() : starts; const isPast = ends < now; const isHighlighted = item.id === highlightedId; const isCurrent = starts <= now && now <= ends; return <li className={`${isPast ? 'is-past' : ''}${isHighlighted ? ' is-highlighted' : ''}`} key={item.id}><div className="schedule-timeline-marker" aria-hidden="true" /><article><div className="schedule-item-time"><time dateTime={item.startsAt}>{formatTime(item.startsAt, wedding.timezone)}</time>{item.endsAt && <span>– {formatTime(item.endsAt, wedding.timezone)}</span>}{isHighlighted && <strong>{isCurrent ? 'Jetzt' : 'Als Nächstes'}</strong>}</div><span className="schedule-item-event">{item.eventTitle}</span><h3>{item.title}</h3>{item.location && <p className="schedule-item-location"><span aria-hidden="true">⌖</span>{item.location}</p>}{item.description && <p className="schedule-item-description">{item.description}</p>}</article></li>; })}</ol></section>)}</div>}
            </main>
        </>
    );
}
