import { Head, Link, router, useForm, usePage } from '@inertiajs/react';
import type { FormEvent, MouseEvent } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import '../../../css/schedule.css';

type ScheduleEvent = { id: string; title: string; startsAt: string };

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 ManagePageProps = {
    wedding: { name: string; timezone: string };
    events: ScheduleEvent[];
    items: ScheduleItem[];
    summary: { total: number; drafts: number; published: number };
    flash: { success: string | null };
    errors: Record<string, string>;
};

type ScheduleForm = {
    event_id: string;
    title: string;
    description: string;
    starts_at: string;
    ends_at: string;
    location: string;
    is_published: boolean;
};

type StatusFilter = 'all' | 'draft' | 'published';

const emptyForm = (events: ScheduleEvent[]): ScheduleForm => ({
    event_id: events[0]?.id ?? '',
    title: '',
    description: '',
    starts_at: '',
    ends_at: '',
    location: '',
    is_published: false,
});

const normalize = (value: string) => value.trim().toLocaleLowerCase('de-DE');

const toDateTimeInput = (value: string | null, timeZone: string) => {
    if (!value) return '';
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return '';
    try {
        const parts = new Intl.DateTimeFormat('de-DE', {
            timeZone,
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            hourCycle: 'h23',
        }).formatToParts(date);
        const part = (type: Intl.DateTimeFormatPartTypes) => parts.find((entry) => entry.type === type)?.value ?? '';
        return `${part('year')}-${part('month')}-${part('day')}T${part('hour')}:${part('minute')}`;
    } catch {
        return value.slice(0, 16);
    }
};

const formatDateTime = (value: string, timeZone: string) => {
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return 'Zeitpunkt nicht verfügbar';
    try {
        return new Intl.DateTimeFormat('de-DE', {
            timeZone,
            day: '2-digit',
            month: 'short',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
        }).format(date);
    } catch {
        return new Intl.DateTimeFormat('de-DE', { dateStyle: 'medium', timeStyle: 'short' }).format(date);
    }
};

export default function ScheduleManage() {
    const { wedding, events, items, summary, flash, errors } = usePage<ManagePageProps>().props;
    const initial = emptyForm(events);
    const form = useForm<ScheduleForm>(initial);
    const [baseline, setBaseline] = useState(initial);
    const [editingId, setEditingId] = useState<string | null>(null);
    const [deletingId, setDeletingId] = useState<string | null>(null);
    const [search, setSearch] = useState('');
    const [eventFilter, setEventFilter] = useState('all');
    const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
    const editorHeading = useRef<HTMLHeadingElement>(null);

    const isDirty = (Object.keys(baseline) as Array<keyof ScheduleForm>).some((key) => form.data[key] !== baseline[key]);
    const generalError = errors.schedule ?? errors.item ?? errors.general;
    const filteredItems = useMemo(() => {
        const query = normalize(search);
        return [...items]
            .filter((item) => {
                const matchesSearch = !query
                    || normalize(item.title).includes(query)
                    || normalize(item.description ?? '').includes(query)
                    || normalize(item.location ?? '').includes(query);
                const matchesEvent = eventFilter === 'all' || item.eventId === eventFilter;
                const matchesStatus = statusFilter === 'all'
                    || (statusFilter === 'published' ? item.isPublished : !item.isPublished);
                return matchesSearch && matchesEvent && matchesStatus;
            })
            .sort((left, right) => new Date(left.startsAt).getTime() - new Date(right.startsAt).getTime());
    }, [eventFilter, items, search, statusFilter]);

    useEffect(() => {
        const warnBeforeUnload = (event: BeforeUnloadEvent) => {
            if (!isDirty) return;
            event.preventDefault();
            event.returnValue = '';
        };
        window.addEventListener('beforeunload', warnBeforeUnload);
        return () => window.removeEventListener('beforeunload', warnBeforeUnload);
    }, [isDirty]);

    const setCleanForm = (data: ScheduleForm, itemId: string | null) => {
        form.clearErrors();
        form.setData(data);
        setBaseline({ ...data });
        setEditingId(itemId);
    };

    const startEditing = (item: ScheduleItem) => {
        setCleanForm({
            event_id: item.eventId,
            title: item.title,
            description: item.description ?? '',
            starts_at: toDateTimeInput(item.startsAt, wedding.timezone),
            ends_at: toDateTimeInput(item.endsAt, wedding.timezone),
            location: item.location ?? '',
            is_published: item.isPublished,
        }, item.id);
        window.scrollTo({ top: 0, behavior: 'smooth' });
        window.setTimeout(() => editorHeading.current?.focus(), 180);
    };

    const resetEditor = () => {
        setCleanForm(emptyForm(events), null);
        editorHeading.current?.focus();
    };

    const submit = (submitEvent: FormEvent<HTMLFormElement>) => {
        submitEvent.preventDefault();
        if (form.processing || events.length === 0) return;
        const options = { preserveScroll: true, onSuccess: resetEditor };
        if (editingId === null) form.post('/ablaufpunkte', options);
        else form.put(`/ablaufpunkte/${editingId}`, options);
    };

    const deleteItem = (item: ScheduleItem) => {
        if (deletingId !== null || form.processing) return;
        if (!window.confirm(`Möchtest du „${item.title}“ wirklich löschen? Diese Aktion kann nicht rückgängig gemacht werden.`)) return;
        setDeletingId(item.id);
        router.delete(`/ablaufpunkte/${item.id}`, {
            preserveScroll: true,
            onSuccess: () => { if (editingId === item.id) resetEditor(); },
            onFinish: () => setDeletingId(null),
        });
    };

    const handleBack = (clickEvent: MouseEvent<Element>) => {
        if (isDirty && !window.confirm('Es gibt ungespeicherte Änderungen. Möchtest du die Seite wirklich verlassen?')) clickEvent.preventDefault();
    };

    return (
        <>
            <Head title="Ablauf verwalten" />
            <main className="schedule-manage-shell">
                <nav className="schedule-nav" aria-label="Bereichsnavigation">
                    <div><span className="schedule-eyebrow">{wedding.name}</span><strong>Ablaufverwaltung</strong></div>
                    <Link className="schedule-secondary-button" href="/dashboard" onClick={handleBack}>Zurück zum Dashboard</Link>
                </nav>

                <div className="schedule-manage-layout">
                    <section className="schedule-editor-panel" aria-labelledby="schedule-editor-title">
                        <div className="schedule-section-heading"><div><span className="schedule-eyebrow">{editingId ? 'Ablaufpunkt bearbeiten' : 'Neuer Ablaufpunkt'}</span><h1 id="schedule-editor-title" ref={editorHeading} tabIndex={-1}>{editingId ? 'Details aktualisieren' : 'Programmpunkt anlegen'}</h1></div>{isDirty && <span className="schedule-unsaved-badge">Ungespeichert</span>}</div>
                        <p className="schedule-editor-copy">Plane Zeiten und Inhalte für eine konkrete Veranstaltung.</p>
                        {flash.success && <div className="alert schedule-success" role="status">{flash.success}</div>}
                        {generalError && <div className="alert alert-danger schedule-error-alert" role="alert">{generalError}</div>}

                        {events.length === 0 ? <div className="schedule-empty-state"><span aria-hidden="true">◇</span><h2>Keine Veranstaltung verfügbar</h2><p>Ein Ablaufpunkt benötigt zunächst eine Veranstaltung.</p></div> : (
                            <form aria-busy={form.processing} noValidate onSubmit={submit}>
                                <div className="schedule-field"><label htmlFor="schedule-event">Veranstaltung</label><select className={`form-select${form.errors.event_id ? ' is-invalid' : ''}`} id="schedule-event" onChange={(event) => form.setData('event_id', event.target.value)} value={form.data.event_id}>{events.map((event) => <option key={event.id} value={event.id}>{event.title} · {formatDateTime(event.startsAt, wedding.timezone)}</option>)}</select>{form.errors.event_id && <div className="invalid-feedback">{form.errors.event_id}</div>}</div>
                                <div className="schedule-field"><label htmlFor="schedule-title">Titel</label><input className={`form-control${form.errors.title ? ' is-invalid' : ''}`} id="schedule-title" onChange={(event) => form.setData('title', event.target.value)} placeholder="z. B. Sektempfang" value={form.data.title} />{form.errors.title && <div className="invalid-feedback">{form.errors.title}</div>}</div>
                                <div className="schedule-field"><label htmlFor="schedule-description">Beschreibung <span>optional</span></label><textarea className={`form-control${form.errors.description ? ' is-invalid' : ''}`} id="schedule-description" onChange={(event) => form.setData('description', event.target.value)} placeholder="Hinweise für eure Gäste" rows={4} value={form.data.description} />{form.errors.description && <div className="invalid-feedback">{form.errors.description}</div>}</div>
                                <div className="schedule-date-grid"><div className="schedule-field"><label htmlFor="schedule-start">Beginn</label><input className={`form-control${form.errors.starts_at ? ' is-invalid' : ''}`} id="schedule-start" onChange={(event) => form.setData('starts_at', event.target.value)} type="datetime-local" value={form.data.starts_at} />{form.errors.starts_at && <div className="invalid-feedback">{form.errors.starts_at}</div>}</div><div className="schedule-field"><label htmlFor="schedule-end">Ende <span>optional</span></label><input className={`form-control${form.errors.ends_at ? ' is-invalid' : ''}`} id="schedule-end" onChange={(event) => form.setData('ends_at', event.target.value)} type="datetime-local" value={form.data.ends_at} />{form.errors.ends_at && <div className="invalid-feedback">{form.errors.ends_at}</div>}</div></div>
                                <div className="schedule-field"><label htmlFor="schedule-location">Ort <span>optional</span></label><input className={`form-control${form.errors.location ? ' is-invalid' : ''}`} id="schedule-location" onChange={(event) => form.setData('location', event.target.value)} placeholder="z. B. Terrasse" value={form.data.location} />{form.errors.location && <div className="invalid-feedback">{form.errors.location}</div>}</div>
                                <fieldset className="schedule-status-picker"><legend>Status</legend><label className={!form.data.is_published ? 'is-selected' : ''}><input checked={!form.data.is_published} name="schedule-status" onChange={() => form.setData('is_published', false)} type="radio" /><span><strong>Entwurf</strong><small>Nur in der Verwaltung sichtbar</small></span></label><label className={form.data.is_published ? 'is-selected is-published' : ''}><input checked={form.data.is_published} name="schedule-status" onChange={() => form.setData('is_published', true)} type="radio" /><span><strong>Veröffentlicht</strong><small>Für berechtigte Gäste sichtbar</small></span></label>{form.errors.is_published && <div className="schedule-field-error">{form.errors.is_published}</div>}</fieldset>
                                <div className="schedule-editor-actions">{editingId && <button className="schedule-text-button" disabled={form.processing} onClick={resetEditor} type="button">Bearbeitung abbrechen</button>}<button className="schedule-primary-button" disabled={form.processing} type="submit">{form.processing ? <><span className="spinner-border spinner-border-sm" aria-hidden="true" /> Wird gespeichert …</> : editingId ? 'Änderungen speichern' : 'Ablaufpunkt erstellen'}</button></div>
                            </form>
                        )}
                    </section>

                    <section className="schedule-list-panel" aria-labelledby="schedule-list-title">
                        <div className="schedule-section-heading"><div><span className="schedule-eyebrow">Zeitplan</span><h2 id="schedule-list-title">Alle Ablaufpunkte</h2></div><span className="schedule-count-badge">{summary.total}</span></div>
                        <dl className="schedule-summary"><div><dt>Gesamt</dt><dd>{summary.total}</dd></div><div><dt>Entwürfe</dt><dd>{summary.drafts}</dd></div><div><dt>Veröffentlicht</dt><dd>{summary.published}</dd></div></dl>
                        <div className="schedule-filters"><div><label htmlFor="schedule-search">Ablauf durchsuchen</label><input id="schedule-search" onChange={(event) => setSearch(event.target.value)} placeholder="Titel, Beschreibung oder Ort …" type="search" value={search} /></div><div><label htmlFor="schedule-event-filter">Veranstaltung</label><select className="form-select" id="schedule-event-filter" onChange={(event) => setEventFilter(event.target.value)} value={eventFilter}><option value="all">Alle Veranstaltungen</option>{events.map((event) => <option key={event.id} value={event.id}>{event.title}</option>)}</select></div><div><label htmlFor="schedule-status-filter">Status</label><select className="form-select" id="schedule-status-filter" onChange={(event) => setStatusFilter(event.target.value as StatusFilter)} value={statusFilter}><option value="all">Alle Status</option><option value="draft">Entwürfe</option><option value="published">Veröffentlicht</option></select></div></div>
                        {items.length === 0 ? <div className="schedule-empty-state"><span aria-hidden="true">◇</span><h3>Noch keine Ablaufpunkte</h3><p>Der erste gespeicherte Programmpunkt erscheint hier.</p></div> : filteredItems.length === 0 ? <div className="schedule-empty-state is-filtered"><h3>Keine passenden Ablaufpunkte</h3><p>Ändere die Suche oder einen Filter.</p></div> : <div className="schedule-managed-list">{filteredItems.map((item) => <article className={`schedule-managed-card ${item.isPublished ? 'is-published' : 'is-draft'}${editingId === item.id ? ' is-editing' : ''}`} key={item.id}><div className="schedule-card-topline"><span className="schedule-status-badge"><i aria-hidden="true" />{item.isPublished ? 'Veröffentlicht' : 'Entwurf'}</span><span>{item.eventTitle}</span></div><div className="schedule-card-time"><time dateTime={item.startsAt}>{formatDateTime(item.startsAt, wedding.timezone)}</time>{item.endsAt && <span>bis {formatDateTime(item.endsAt, wedding.timezone)}</span>}</div><h3>{item.title}</h3>{item.location && <p className="schedule-card-location"><span aria-hidden="true">⌖</span>{item.location}</p>}{item.description && <p className="schedule-card-description">{item.description}</p>}<div className="schedule-card-actions"><button className="schedule-text-button" disabled={form.processing || deletingId !== null} onClick={() => startEditing(item)} type="button">Bearbeiten</button><button className="schedule-text-button is-danger" disabled={form.processing || deletingId !== null} onClick={() => deleteItem(item)} type="button">{deletingId === item.id ? 'Wird gelöscht …' : 'Löschen'}</button></div></article>)}</div>}
                    </section>
                </div>
            </main>
        </>
    );
}
