import { Head, Link, router, useForm, usePage } from '@inertiajs/react';
import type { FormEvent } from 'react';
import { useState } from 'react';

type GuestDraft = {
    id?: string;
    first_name: string;
    last_name: string;
    email: string;
    is_child: boolean;
    can_login: boolean;
    is_primary: boolean;
};

type GuestGroup = {
    id: string;
    label: string;
    salutation: string | null;
    guests: Array<{
        id: string;
        name: string;
        firstName: string;
        lastName: string | null;
        email: string | null;
        isChild: boolean;
        canLogin: boolean;
        isPrimary: boolean;
    }>;
    contacts: Array<{
        name: string;
        userId: number;
        email: string;
        isPrimary: boolean;
        invitationStatus: string;
        canRevoke: boolean;
    }>;
};

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

const emptyGuest = (): GuestDraft => ({
    first_name: '',
    last_name: '',
    email: '',
    is_child: false,
    can_login: true,
    is_primary: false,
});

export default function GuestIndex() {
    const { wedding, groups, flash, errors } = usePage<PageProps>().props;
    const [editingId, setEditingId] = useState<string | null>(null);
    const [pendingAction, setPendingAction] = useState<string | null>(null);
    const form = useForm<{ label: string; salutation: string; guests: GuestDraft[] }>({
        label: '',
        salutation: '',
        guests: [{ ...emptyGuest(), is_primary: true }],
    });

    const updateGuest = <K extends keyof GuestDraft>(index: number, field: K, value: GuestDraft[K]) => {
        const guests = form.data.guests.map((guest, guestIndex) => {
            if (guestIndex !== index) return guest;

            const next = { ...guest, [field]: value };
            if (field === 'is_child' && value === true) {
                next.can_login = false;
                next.is_primary = false;
                next.email = '';
            }
            if (field === 'can_login' && value === false) next.is_primary = false;

            return next;
        });

        form.setData('guests', guests);
    };

    const selectPrimary = (index: number) => {
        form.setData('guests', form.data.guests.map((guest, guestIndex) => ({
            ...guest,
            is_primary: guestIndex === index,
        })));
    };

    const removeGuest = (index: number) => {
        if (form.data.guests.length === 1) return;
        const guests = form.data.guests.filter((_, guestIndex) => guestIndex !== index);
        if (!guests.some((guest) => guest.is_primary)) {
            const firstLogin = guests.findIndex((guest) => guest.can_login);
            if (firstLogin >= 0) guests[firstLogin] = { ...guests[firstLogin], is_primary: true };
        }
        form.setData('guests', guests);
    };

    const submit = (event: FormEvent) => {
        event.preventDefault();
        const options = {
            preserveScroll: true,
            onSuccess: () => {
                form.reset();
                setEditingId(null);
            },
        };

        editingId === null
            ? form.post('/gaeste', options)
            : form.put(`/gaeste/${editingId}`, options);
    };

    const startEditing = (group: GuestGroup) => {
        setEditingId(group.id);
        form.clearErrors();
        form.setData({
            label: group.label,
            salutation: group.salutation ?? '',
            guests: group.guests.map((guest) => ({
                id: guest.id,
                first_name: guest.firstName,
                last_name: guest.lastName ?? '',
                email: guest.email ?? '',
                is_child: guest.isChild,
                can_login: guest.canLogin,
                is_primary: guest.isPrimary,
            })),
        });
        window.scrollTo({ top: 0, behavior: 'smooth' });
    };

    const cancelEditing = () => {
        setEditingId(null);
        form.clearErrors();
        form.reset();
    };

    const resendInvitation = (groupId: string, userId: number) => {
        const actionKey = `resend-${groupId}-${userId}`;
        setPendingAction(actionKey);
        router.post(`/gaeste/${groupId}/einladungen/${userId}/erneut-senden`, {}, {
            preserveScroll: true,
            onFinish: () => setPendingAction(null),
        });
    };

    const revokeInvitation = (groupId: string, userId: number, email: string) => {
        if (!window.confirm(`Einladungslink für ${email} wirklich widerrufen?`)) return;

        const actionKey = `revoke-${groupId}-${userId}`;
        setPendingAction(actionKey);
        router.delete(`/gaeste/${groupId}/einladungen/${userId}`, {
            preserveScroll: true,
            onFinish: () => setPendingAction(null),
        });
    };

    const fieldError = (index: number, field: keyof GuestDraft) =>
        form.errors[`guests.${index}.${field}` as keyof typeof form.errors] as string | undefined;

    return (
        <>
            <Head title="Gäste verwalten" />
            <main className="management-shell">
                <nav className="dashboard-nav" aria-label="Hauptnavigation">
                    <div>
                        <span className="eyebrow">{wedding?.name}</span>
                        <strong>Gästeverwaltung</strong>
                    </div>
                    <Link className="secondary-action text-decoration-none" href="/dashboard">Übersicht</Link>
                </nav>

                <div className="management-grid">
                    <section className="management-panel">
                        <span className="eyebrow">{editingId === null ? 'Neue Einladung' : 'Einladung bearbeiten'}</span>
                        <h1 className="management-title">{editingId === null ? 'Paar oder Familie anlegen' : 'Gruppe aktualisieren'}</h1>
                        <p className="section-copy">Alle Personen einer Einladung bleiben als Gruppe zusammen. Erwachsene können jeweils einen eigenen Zugang bekommen.</p>

                        {flash.success && <div className="alert success-note" role="status">{flash.success}</div>}
                        {errors.invitation && <div className="alert alert-danger" role="alert">{errors.invitation}</div>}
                        {form.errors.guests && <div className="alert alert-danger">{form.errors.guests}</div>}

                        <form onSubmit={submit} noValidate>
                            <div className="row g-3 mb-4">
                                <div className="col-md-5">
                                    <label className="form-label" htmlFor="label">Interner Gruppenname</label>
                                    <input
                                        className={`form-control ${form.errors.label ? 'is-invalid' : ''}`}
                                        id="label"
                                        onChange={(event) => form.setData('label', event.target.value)}
                                        placeholder="z. B. Familie Müller"
                                        value={form.data.label}
                                    />
                                    {form.errors.label && <div className="invalid-feedback">{form.errors.label}</div>}
                                </div>
                                <div className="col-md-7">
                                    <label className="form-label" htmlFor="salutation">Persönliche Anrede</label>
                                    <input
                                        className={`form-control ${form.errors.salutation ? 'is-invalid' : ''}`}
                                        id="salutation"
                                        onChange={(event) => form.setData('salutation', event.target.value)}
                                        placeholder="Liebe Anna, lieber Ben und liebe Mia,"
                                        value={form.data.salutation}
                                    />
                                    {form.errors.salutation && <div className="invalid-feedback">{form.errors.salutation}</div>}
                                </div>
                            </div>

                            <div className="guest-editor-list">
                                {form.data.guests.map((guest, index) => (
                                    <fieldset className="guest-editor" key={index}>
                                        <legend>Person {index + 1}</legend>
                                        <button
                                            aria-label={`Person ${index + 1} entfernen`}
                                            className="remove-person"
                                            disabled={form.data.guests.length === 1}
                                            onClick={() => removeGuest(index)}
                                            type="button"
                                        >×</button>
                                        <div className="row g-3">
                                            <div className="col-sm-6">
                                                <label className="form-label" htmlFor={`first-name-${index}`}>Vorname</label>
                                                <input
                                                    className={`form-control ${fieldError(index, 'first_name') ? 'is-invalid' : ''}`}
                                                    id={`first-name-${index}`}
                                                    onChange={(event) => updateGuest(index, 'first_name', event.target.value)}
                                                    value={guest.first_name}
                                                />
                                                {fieldError(index, 'first_name') && <div className="invalid-feedback">{fieldError(index, 'first_name')}</div>}
                                            </div>
                                            <div className="col-sm-6">
                                                <label className="form-label" htmlFor={`last-name-${index}`}>Nachname</label>
                                                <input
                                                    className="form-control"
                                                    id={`last-name-${index}`}
                                                    onChange={(event) => updateGuest(index, 'last_name', event.target.value)}
                                                    value={guest.last_name}
                                                />
                                            </div>
                                            <div className="col-12">
                                                <label className="form-label" htmlFor={`email-${index}`}>E-Mail-Adresse {guest.can_login && '(für den Zugang)'}</label>
                                                <input
                                                    className={`form-control ${fieldError(index, 'email') ? 'is-invalid' : ''}`}
                                                    disabled={!guest.can_login}
                                                    id={`email-${index}`}
                                                    onChange={(event) => updateGuest(index, 'email', event.target.value)}
                                                    type="email"
                                                    value={guest.email}
                                                />
                                                {fieldError(index, 'email') && <div className="invalid-feedback">{fieldError(index, 'email')}</div>}
                                            </div>
                                        </div>
                                        <div className="guest-options">
                                            <label className="form-check">
                                                <input
                                                    checked={guest.is_child}
                                                    className="form-check-input"
                                                    onChange={(event) => updateGuest(index, 'is_child', event.target.checked)}
                                                    type="checkbox"
                                                />
                                                <span className="form-check-label">Kind</span>
                                            </label>
                                            <label className="form-check">
                                                <input
                                                    checked={guest.can_login}
                                                    className="form-check-input"
                                                    disabled={guest.is_child}
                                                    onChange={(event) => updateGuest(index, 'can_login', event.target.checked)}
                                                    type="checkbox"
                                                />
                                                <span className="form-check-label">Eigener Zugang</span>
                                            </label>
                                            <label className="form-check">
                                                <input
                                                    checked={guest.is_primary}
                                                    className="form-check-input"
                                                    disabled={!guest.can_login}
                                                    name="primary-contact"
                                                    onChange={() => selectPrimary(index)}
                                                    type="radio"
                                                />
                                                <span className="form-check-label">Hauptkontakt</span>
                                            </label>
                                        </div>
                                    </fieldset>
                                ))}
                            </div>

                            <div className="form-actions">
                                <div className="d-flex flex-wrap gap-2">
                                    <button className="secondary-action" onClick={() => form.setData('guests', [...form.data.guests, emptyGuest()])} type="button">
                                        + Person hinzufügen
                                    </button>
                                    {editingId !== null && <button className="secondary-action" onClick={cancelEditing} type="button">Abbrechen</button>}
                                </div>
                                <button className="primary-action m-0" disabled={form.processing} type="submit">
                                    {form.processing
                                        ? 'Wird gespeichert …'
                                        : editingId === null ? 'Gruppe anlegen & einladen' : 'Änderungen speichern'}
                                </button>
                            </div>
                        </form>
                    </section>

                    <aside className="group-overview">
                        <div className="overview-heading">
                            <span className="eyebrow">Bereits angelegt</span>
                            <strong>{groups.length} {groups.length === 1 ? 'Gruppe' : 'Gruppen'}</strong>
                        </div>
                        {groups.length === 0 && <p className="empty-state">Noch keine Gäste angelegt.</p>}
                        {groups.map((group) => (
                            <article className="group-card" key={group.id}>
                                <div className="group-card-heading">
                                    <h2>{group.label}</h2>
                                    <button className="text-action" onClick={() => startEditing(group)} type="button">Bearbeiten</button>
                                </div>
                                {group.salutation && <p>{group.salutation}</p>}
                                <div className="chip-row">
                                    {group.guests.map((guest) => (
                                        <span className="guest-chip" key={guest.id}>{guest.name}{guest.isChild ? ' · Kind' : ''}</span>
                                    ))}
                                </div>
                                <div className="contact-list">
                                    {group.contacts.map((contact) => (
                                        <div className="contact-row" key={contact.email}>
                                            <div><strong>{contact.name}</strong><small>{contact.email}</small></div>
                                            <div className="contact-actions">
                                                <span className="status-badge">{contact.invitationStatus}</span>
                                                <button
                                                    className="text-action"
                                                    disabled={pendingAction !== null}
                                                    onClick={() => resendInvitation(group.id, contact.userId)}
                                                    type="button"
                                                >{pendingAction === `resend-${group.id}-${contact.userId}` ? 'Wird gesendet …' : 'Erneut senden'}</button>
                                                {contact.canRevoke && (
                                                    <button
                                                        className="text-action text-action-danger"
                                                        disabled={pendingAction !== null}
                                                        onClick={() => revokeInvitation(group.id, contact.userId, contact.email)}
                                                        type="button"
                                                    >Widerrufen</button>
                                                )}
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </article>
                        ))}
                    </aside>
                </div>
            </main>
        </>
    );
}
