import { Head, Link, useForm, usePage } from '@inertiajs/react';
import type { FormEvent } from 'react';
import { useRef, useState } from 'react';
import '../../../css/events.css';

type EventItem = {
    id: string;
    title: string;
    description: string | null;
    startsAt: string;
    endsAt: string | null;
    venueName: string | null;
    venueAddress: string | null;
    isPublished: boolean;
    invitedGroupCount: number;
    invitedGuestCount: number;
    photoBoxEnabled: boolean;
};

type PageProps = {
    wedding: {
        name: string;
        timezone: string;
    } | null;
    events: EventItem[];
    flash: {
        success: string | null;
    };
    errors: Record<string, string>;
};

type EventForm = {
    title: string;
    description: string;
    starts_at: string;
    ends_at: string;
    venue_name: string;
    venue_address: string;
    is_published: boolean;
    photo_box_enabled: boolean;
};

const emptyForm: EventForm = {
    title: '',
    description: '',
    starts_at: '',
    ends_at: '',
    venue_name: '',
    venue_address: '',
    is_published: false,
    photo_box_enabled: false,
};

const dateTimeInputValue = (value: string | null, timeZone: string): 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((item) => item.type === type)?.value ?? '';

        return `${part('year')}-${part('month')}-${part('day')}T${part('hour')}:${part('minute')}`;
    } catch {
        return value.slice(0, 16);
    }
};

const formatEventDate = (value: string, timeZone: string): string => {
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return 'Datum noch nicht verfügbar';

    try {
        return new Intl.DateTimeFormat('de-DE', {
            timeZone,
            weekday: 'short',
            day: '2-digit',
            month: 'short',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
        }).format(date);
    } catch {
        return new Intl.DateTimeFormat('de-DE', {
            day: '2-digit',
            month: 'short',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
        }).format(date);
    }
};

export default function EventIndex() {
    const { wedding, events, flash, errors } = usePage<PageProps>().props;
    const [editingId, setEditingId] = useState<string | null>(null);
    const titleInput = useRef<HTMLInputElement>(null);
    const timeZone = wedding?.timezone || 'Europe/Berlin';
    const form = useForm<EventForm>(emptyForm);

    const submit = (event: FormEvent<HTMLFormElement>) => {
        event.preventDefault();

        if (editingId === null) {
            form.post('/veranstaltungen', {
                preserveScroll: true,
                onSuccess: () => form.reset(),
            });
            return;
        }

        form.put(`/veranstaltungen/${editingId}`, {
            preserveScroll: true,
            onSuccess: () => {
                setEditingId(null);
                form.reset();
            },
        });
    };

    const editEvent = (item: EventItem) => {
        setEditingId(item.id);
        form.clearErrors();
        form.setData({
            title: item.title,
            description: item.description ?? '',
            starts_at: dateTimeInputValue(item.startsAt, timeZone),
            ends_at: dateTimeInputValue(item.endsAt, timeZone),
            venue_name: item.venueName ?? '',
            venue_address: item.venueAddress ?? '',
            is_published: item.isPublished,
            photo_box_enabled: item.photoBoxEnabled,
        });
        window.scrollTo({ top: 0, behavior: 'smooth' });
        window.setTimeout(() => titleInput.current?.focus(), 250);
    };

    const cancelEditing = () => {
        setEditingId(null);
        form.clearErrors();
        form.reset();
        titleInput.current?.focus();
    };

    const fieldClass = (field: keyof EventForm) => `form-control${form.errors[field] ? ' is-invalid' : ''}`;
    const generalError = errors.event ?? errors.events ?? errors.general;

    return (
        <>
            <Head title="Veranstaltungen verwalten" />
            <main className="events-shell">
                <nav className="events-nav" aria-label="Bereichsnavigation">
                    <div>
                        <span className="events-eyebrow">{wedding?.name ?? 'Unsere Hochzeit'}</span>
                        <strong>Veranstaltungen</strong>
                    </div>
                    <Link className="events-secondary-button" href="/dashboard">Zur Übersicht</Link>
                </nav>

                <div className="events-layout">
                    <section className="events-editor" aria-labelledby="event-form-title">
                        <div className="events-section-heading">
                            <div>
                                <span className="events-eyebrow">{editingId === null ? 'Neue Veranstaltung' : 'Veranstaltung bearbeiten'}</span>
                                <h1 id="event-form-title">{editingId === null ? 'Termin anlegen' : 'Details aktualisieren'}</h1>
                            </div>
                            {editingId !== null && (
                                <button className="events-text-button" onClick={cancelEditing} type="button">Bearbeiten abbrechen</button>
                            )}
                        </div>
                        <p className="events-intro">Plane alle Programmpunkte und entscheide, wann sie für eingeladene Gäste sichtbar werden.</p>

                        {flash.success && <div className="alert events-success" role="status">{flash.success}</div>}
                        {generalError && <div className="alert alert-danger" role="alert">{generalError}</div>}

                        <form aria-busy={form.processing} noValidate onSubmit={submit}>
                            <div className="row g-3">
                                <div className="col-12">
                                    <label className="form-label" htmlFor="event-title">Titel</label>
                                    <input
                                        autoComplete="off"
                                        className={fieldClass('title')}
                                        id="event-title"
                                        onChange={(event) => form.setData('title', event.target.value)}
                                        placeholder="z. B. Freie Trauung"
                                        ref={titleInput}
                                        required
                                        value={form.data.title}
                                    />
                                    {form.errors.title && <div className="invalid-feedback">{form.errors.title}</div>}
                                </div>

                                <div className="col-12">
                                    <label className="form-label" htmlFor="event-description">Beschreibung</label>
                                    <textarea
                                        className={fieldClass('description')}
                                        id="event-description"
                                        onChange={(event) => form.setData('description', event.target.value)}
                                        placeholder="Hinweise zum Ablauf, zur Kleidung oder Anreise"
                                        rows={4}
                                        value={form.data.description}
                                    />
                                    {form.errors.description && <div className="invalid-feedback">{form.errors.description}</div>}
                                </div>

                                <div className="col-md-6">
                                    <label className="form-label" htmlFor="event-start">Beginn</label>
                                    <input
                                        className={fieldClass('starts_at')}
                                        id="event-start"
                                        onChange={(event) => form.setData('starts_at', event.target.value)}
                                        required
                                        type="datetime-local"
                                        value={form.data.starts_at}
                                    />
                                    {form.errors.starts_at && <div className="invalid-feedback">{form.errors.starts_at}</div>}
                                </div>

                                <div className="col-md-6">
                                    <label className="form-label" htmlFor="event-end">Ende <span className="events-optional">optional</span></label>
                                    <input
                                        className={fieldClass('ends_at')}
                                        id="event-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 className="col-md-5">
                                    <label className="form-label" htmlFor="event-venue">Ort</label>
                                    <input
                                        autoComplete="organization"
                                        className={fieldClass('venue_name')}
                                        id="event-venue"
                                        onChange={(event) => form.setData('venue_name', event.target.value)}
                                        placeholder="Name der Location"
                                        value={form.data.venue_name}
                                    />
                                    {form.errors.venue_name && <div className="invalid-feedback">{form.errors.venue_name}</div>}
                                </div>

                                <div className="col-md-7">
                                    <label className="form-label" htmlFor="event-address">Adresse</label>
                                    <input
                                        autoComplete="street-address"
                                        className={fieldClass('venue_address')}
                                        id="event-address"
                                        onChange={(event) => form.setData('venue_address', event.target.value)}
                                        placeholder="Straße, Hausnummer, Ort"
                                        value={form.data.venue_address}
                                    />
                                    {form.errors.venue_address && <div className="invalid-feedback">{form.errors.venue_address}</div>}
                                </div>
                            </div>

                            <fieldset className="events-visibility">
                                <legend>Sichtbarkeit</legend>
                                <label className={`events-status-choice${!form.data.is_published ? ' is-selected' : ''}`}>
                                    <input
                                        checked={!form.data.is_published}
                                        className="form-check-input"
                                        name="event-status"
                                        onChange={() => form.setData('is_published', false)}
                                        type="radio"
                                    />
                                    <span><strong>Entwurf</strong><small>Nur in der Verwaltung sichtbar</small></span>
                                </label>
                                <label className={`events-status-choice${form.data.is_published ? ' is-selected' : ''}`}>
                                    <input
                                        checked={form.data.is_published}
                                        className="form-check-input"
                                        name="event-status"
                                        onChange={() => form.setData('is_published', true)}
                                        type="radio"
                                    />
                                    <span><strong>Veröffentlicht</strong><small>Für eingeladene Gäste sichtbar</small></span>
                                </label>
                                {form.errors.is_published && <div className="events-field-error" role="alert">{form.errors.is_published}</div>}
                            </fieldset>

                            <label className={`events-photo-box-toggle${form.data.photo_box_enabled ? ' is-selected' : ''}`}>
                                <input
                                    checked={form.data.photo_box_enabled}
                                    className="form-check-input"
                                    onChange={(event) => form.setData('photo_box_enabled', event.target.checked)}
                                    type="checkbox"
                                />
                                <span><strong>Fotobox für diese Veranstaltung aktivieren</strong><small>Eingeladene Gäste können anschließend Fotos ansehen und – mit entsprechender Berechtigung – hochladen.</small></span>
                            </label>
                            {form.errors.photo_box_enabled && <div className="events-field-error" role="alert">{form.errors.photo_box_enabled}</div>}

                            <div className="events-form-actions">
                                <p>Zeiten werden in <strong>{timeZone}</strong> gepflegt.</p>
                                <button className="events-primary-button" disabled={form.processing} type="submit">
                                    {form.processing
                                        ? 'Wird gespeichert …'
                                        : editingId === null ? 'Veranstaltung anlegen' : 'Änderungen speichern'}
                                </button>
                            </div>
                        </form>
                    </section>

                    <section className="events-overview" aria-labelledby="event-list-title">
                        <div className="events-list-heading">
                            <div>
                                <span className="events-eyebrow">Zeitplan</span>
                                <h2 id="event-list-title">Vorhandene Veranstaltungen</h2>
                            </div>
                            <span className="events-count" aria-label={`${events.length} Veranstaltungen`}>{events.length}</span>
                        </div>

                        {events.length === 0 ? (
                            <div className="events-empty">
                                <span aria-hidden="true">◇</span>
                                <h3>Noch keine Veranstaltung</h3>
                                <p>Lege links beziehungsweise oben den ersten Programmpunkt für eure Hochzeit an.</p>
                            </div>
                        ) : (
                            <div className="events-list">
                                {events.map((item) => (
                                    <article className={`event-card${editingId === item.id ? ' is-editing' : ''}`} key={item.id}>
                                        <div className="event-card-topline">
                                            <div className="event-card-statuses">
                                                <span className={`event-status ${item.isPublished ? 'is-published' : 'is-draft'}`}><span aria-hidden="true" />{item.isPublished ? 'Veröffentlicht' : 'Entwurf'}</span>
                                                <span className={`event-photo-box-status ${item.photoBoxEnabled ? 'is-active' : ''}`}><span aria-hidden="true" />Fotobox {item.photoBoxEnabled ? 'aktiv' : 'inaktiv'}</span>
                                            </div>
                                            <button
                                                aria-label={`${item.title} bearbeiten`}
                                                className="events-text-button"
                                                disabled={form.processing}
                                                onClick={() => editEvent(item)}
                                                type="button"
                                            >Bearbeiten</button>
                                        </div>
                                        <h3>{item.title}</h3>
                                        <p className="event-time">
                                            <span>Beginn</span>
                                            <strong>{formatEventDate(item.startsAt, timeZone)}</strong>
                                            {item.endsAt && <small>bis {formatEventDate(item.endsAt, timeZone)}</small>}
                                        </p>
                                        {(item.venueName || item.venueAddress) && (
                                            <p className="event-location">
                                                <span aria-hidden="true">⌖</span>
                                                <span>{item.venueName && <strong>{item.venueName}</strong>}{item.venueAddress && <small>{item.venueAddress}</small>}</span>
                                            </p>
                                        )}
                                        {item.description && <p className="event-description">{item.description}</p>}
                                        <dl className="event-invitations" aria-label="Einladungszahlen">
                                            <div><dt>Gruppen</dt><dd>{item.invitedGroupCount}</dd></div>
                                            <div><dt>Personen</dt><dd>{item.invitedGuestCount}</dd></div>
                                        </dl>
                                        <div className="event-card-actions">
                                            <Link className="event-assignments-link" href={`/veranstaltungen/${item.id}/einladung`}>
                                                Einladung gestalten
                                            </Link>
                                            <Link className="event-assignments-link" href={`/veranstaltungen/${item.id}/gaeste`}>
                                                Gäste zuordnen
                                            </Link>
                                            <Link className="event-assignments-link" href={`/veranstaltungen/${item.id}/rueckmeldung`}>
                                                Rückmeldung einrichten
                                            </Link>
                                        </div>
                                    </article>
                                ))}
                            </div>
                        )}
                    </section>
                </div>
            </main>
        </>
    );
}
