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

type RsvpStatus = 'pending' | 'accepted' | 'declined';

type QuestionType = 'text' | 'single_choice' | 'multiple_choice' | 'boolean';

type AnswerValue = string | string[] | boolean | null;

type Question = {
    id: string;
    label: string;
    helpText: string | null;
    type: QuestionType;
    required: boolean;
    options: string[];
};

type InvitedGuestResponse = {
    invitedGuestId: string;
    guestId: string;
    name: string;
    isChild: boolean;
    status: RsvpStatus;
    notes: string;
    answers: Record<string, AnswerValue>;
};

type PageProps = {
    wedding: {
        name: string;
        timezone: string;
    };
    eventInvitation: {
        id: string;
    };
    event: {
        id: string;
        title: string;
        description: string | null;
        startsAt: string;
        endsAt: string | null;
        venueName: string | null;
        venueAddress: string | null;
    };
    group: {
        id: string;
        label: string;
        salutation: string | null;
    };
    guests: InvitedGuestResponse[];
    questions: Question[];
    responseDeadline: string | null;
    isLocked: boolean;
    flash: {
        success: string | null;
    };
    errors: Record<string, string>;
};

type RsvpPayload = {
    responses: Array<{
        event_invited_guest_id: string;
        status: RsvpStatus;
        notes: string;
        answers: Record<string, AnswerValue>;
    }>;
};

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

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

const initialResponses = (guests: InvitedGuestResponse[]): RsvpPayload['responses'] => guests.map((guest) => ({
    event_invited_guest_id: guest.invitedGuestId,
    status: guest.status,
    notes: guest.notes,
    answers: { ...guest.answers },
}));

export default function RsvpShow() {
    const {
        wedding,
        eventInvitation,
        event,
        group,
        guests,
        questions,
        responseDeadline,
        isLocked,
        flash,
        errors,
    } = usePage<PageProps>().props;
    const form = useForm<RsvpPayload>({ responses: initialResponses(guests) });
    const allErrors = { ...errors, ...(form.errors as Record<string, string>) };
    const acceptedCount = form.data.responses.filter((response) => response.status === 'accepted').length;
    const declinedCount = form.data.responses.filter((response) => response.status === 'declined').length;
    const pendingCount = form.data.responses.filter((response) => response.status === 'pending').length;
    const generalError = errors.rsvp ?? errors.responses ?? errors.general;

    const setResponse = (index: number, changes: Partial<RsvpPayload['responses'][number]>) => {
        form.setData('responses', form.data.responses.map((response, responseIndex) =>
            responseIndex === index ? { ...response, ...changes } : response,
        ));
    };

    const setAnswer = (guestIndex: number, questionId: string, value: AnswerValue) => {
        const response = form.data.responses[guestIndex];
        setResponse(guestIndex, { answers: { ...response.answers, [questionId]: value } });
    };

    const toggleMultipleAnswer = (guestIndex: number, questionId: string, option: string, checked: boolean) => {
        const currentValue = form.data.responses[guestIndex].answers[questionId];
        const currentOptions = Array.isArray(currentValue) ? currentValue : [];
        const nextOptions = checked
            ? [...new Set([...currentOptions, option])]
            : currentOptions.filter((currentOption) => currentOption !== option);

        setAnswer(guestIndex, questionId, nextOptions);
    };

    const fieldError = (guestIndex: number, path: string) => allErrors[`responses.${guestIndex}.${path}`];

    const unmatchedPersonErrors = (guestIndex: number) => {
        const prefix = `responses.${guestIndex}.`;
        const knownPaths = new Set([
            `${prefix}status`,
            `${prefix}notes`,
            `${prefix}answers`,
            ...questions.map((question) => `${prefix}answers.${question.id}`),
        ]);

        return [...new Set(Object.entries(allErrors)
            .filter(([key]) => key.startsWith(prefix) && !knownPaths.has(key))
            .map(([, message]) => message)
            .filter(Boolean))];
    };

    const submit = (submitEvent: FormEvent<HTMLFormElement>) => {
        submitEvent.preventDefault();
        if (form.processing || isLocked) return;

        form.put(`/rueckmeldung/${eventInvitation.id}`, { preserveScroll: true });
    };

    return (
        <>
            <Head title={`Rückmeldung · ${event.title}`} />
            <main className="rsvp-shell">
                <nav className="rsvp-nav" aria-label="Bereichsnavigation">
                    <div>
                        <span className="rsvp-eyebrow">{wedding.name}</span>
                        <strong>Rückmeldung</strong>
                    </div>
                    <Link className="rsvp-secondary-button" href="/dashboard">Zur Hochzeitsübersicht</Link>
                </nav>

                <header className="rsvp-event-card">
                    <div className="rsvp-event-main">
                        <span className="rsvp-eyebrow">Ihr seid eingeladen</span>
                        <h1>{event.title}</h1>
                        <p className="rsvp-event-date">{formatDateTime(event.startsAt, wedding.timezone)}</p>
                        {event.endsAt && <p className="rsvp-event-end">bis {formatDateTime(event.endsAt, wedding.timezone, false)}</p>}
                        {(event.venueName || event.venueAddress) && (
                            <p className="rsvp-event-location">
                                <span aria-hidden="true">⌖</span>
                                <span>{event.venueName && <strong>{event.venueName}</strong>}{event.venueAddress && <small>{event.venueAddress}</small>}</span>
                            </p>
                        )}
                    </div>
                    {event.description && <p className="rsvp-event-description">{event.description}</p>}
                </header>

                <section className="rsvp-welcome" aria-labelledby="rsvp-welcome-title">
                    <div className="rsvp-ornament" aria-hidden="true"><span /><i>◇</i><span /></div>
                    <h2 id="rsvp-welcome-title">{group.salutation || `Hallo ${group.label},`}</h2>
                    <p>Gebt bitte für jede Person einzeln an, ob sie dabei sein kann. Alle Antworten werden gemeinsam gespeichert.</p>
                </section>

                {flash.success && <div className="alert rsvp-success" role="status">{flash.success}</div>}
                {generalError && <div className="alert alert-danger rsvp-page-alert" role="alert">{generalError}</div>}
                {isLocked && (
                    <div className="rsvp-locked-note" role="status">
                        <span aria-hidden="true">◇</span>
                        <div><strong>Die Rückmeldefrist ist beendet.</strong><p>Eure Antworten können angesehen, aber nicht mehr geändert werden.</p></div>
                    </div>
                )}

                {guests.length === 0 ? (
                    <section className="rsvp-empty" role="alert">
                        <span aria-hidden="true">◇</span>
                        <h2>Keine eingeladenen Personen gefunden</h2>
                        <p>Für diese Einladung konnten keine Personen geladen werden. Bitte versucht es später erneut oder wendet euch an das Brautpaar.</p>
                    </section>
                ) : (
                    <form aria-busy={form.processing} noValidate onSubmit={submit}>
                        <div className="rsvp-layout">
                            <section className="rsvp-responses" aria-label="Antworten der eingeladenen Personen">
                                {guests.map((guest, guestIndex) => {
                                    const response = form.data.responses[guestIndex];
                                    const accepted = response.status === 'accepted';
                                    const personErrors = unmatchedPersonErrors(guestIndex);

                                    return (
                                        <fieldset className="rsvp-person-card" disabled={isLocked || form.processing} key={guest.invitedGuestId}>
                                            <legend className="visually-hidden">Rückmeldung für {guest.name}</legend>
                                            <div className="rsvp-person-heading">
                                                <div className="rsvp-avatar" aria-hidden="true">{guest.name.trim().charAt(0).toLocaleUpperCase('de-DE') || '◇'}</div>
                                                <div><h2>{guest.name}</h2><p>Persönliche Rückmeldung</p></div>
                                                {guest.isChild && <span className="rsvp-child-badge">Kind</span>}
                                            </div>

                                            {personErrors.length > 0 && (
                                                <div className="alert alert-danger rsvp-person-errors" role="alert">
                                                    <ul>{personErrors.map((message) => <li key={message}>{message}</li>)}</ul>
                                                </div>
                                            )}

                                            <fieldset className="rsvp-status-picker">
                                                <legend>Kann {guest.name} dabei sein?</legend>
                                                <div className="rsvp-status-options">
                                                    {([
                                                        { value: 'pending' as const, label: 'Noch offen', symbol: '○' },
                                                        { value: 'accepted' as const, label: 'Zusage', symbol: '✓' },
                                                        { value: 'declined' as const, label: 'Absage', symbol: '×' },
                                                    ]).map((statusOption) => {
                                                        const inputId = `status-${guest.invitedGuestId}-${statusOption.value}`;
                                                        return (
                                                            <label className={`rsvp-status-option is-${statusOption.value}${response.status === statusOption.value ? ' is-selected' : ''}`} htmlFor={inputId} key={statusOption.value}>
                                                                <input
                                                                    checked={response.status === statusOption.value}
                                                                    id={inputId}
                                                                    name={`status-${guest.invitedGuestId}`}
                                                                    onChange={() => setResponse(guestIndex, { status: statusOption.value })}
                                                                    type="radio"
                                                                />
                                                                <span aria-hidden="true">{statusOption.symbol}</span>
                                                                <strong>{statusOption.label}</strong>
                                                            </label>
                                                        );
                                                    })}
                                                </div>
                                                {fieldError(guestIndex, 'status') && <div className="rsvp-field-error" role="alert">{fieldError(guestIndex, 'status')}</div>}
                                            </fieldset>

                                            {questions.length > 0 && (
                                                <div className={`rsvp-questions${accepted ? '' : ' is-inactive'}`}>
                                                    <div className="rsvp-questions-heading">
                                                        <h3>Weitere Angaben</h3>
                                                        {!accepted && <span>Bei einer Zusage relevant</span>}
                                                    </div>
                                                    {questions.map((question) => {
                                                        const answer = response.answers[question.id];
                                                        const questionError = fieldError(guestIndex, `answers.${question.id}`);
                                                        const questionId = `question-${guest.invitedGuestId}-${question.id}`;
                                                        const required = accepted && question.required;

                                                        return (
                                                            <fieldset className="rsvp-question" key={question.id}>
                                                                <legend id={`${questionId}-label`}>
                                                                    {question.label}
                                                                    {required && <span className="rsvp-required">Pflicht bei Zusage</span>}
                                                                </legend>
                                                                {question.helpText && <p id={`${questionId}-help`}>{question.helpText}</p>}

                                                                {question.type === 'text' && (
                                                                    <textarea
                                                                        aria-describedby={question.helpText ? `${questionId}-help` : undefined}
                                                                        aria-invalid={Boolean(questionError)}
                                                                        aria-required={required}
                                                                        className={`form-control${questionError ? ' is-invalid' : ''}`}
                                                                        id={questionId}
                                                                        onChange={(changeEvent) => setAnswer(guestIndex, question.id, changeEvent.target.value)}
                                                                        rows={3}
                                                                        value={typeof answer === 'string' ? answer : ''}
                                                                    />
                                                                )}

                                                                {question.type === 'single_choice' && (
                                                                    <div aria-labelledby={`${questionId}-label`} className="rsvp-choice-list" role="radiogroup">
                                                                        {question.options.map((option, optionIndex) => {
                                                                            const optionId = `${questionId}-${optionIndex}`;
                                                                            return (
                                                                                <label htmlFor={optionId} key={`${question.id}-${option}`}>
                                                                                    <input
                                                                                        checked={answer === option}
                                                                                        className="form-check-input"
                                                                                        id={optionId}
                                                                                        name={questionId}
                                                                                        onChange={() => setAnswer(guestIndex, question.id, option)}
                                                                                        type="radio"
                                                                                    />
                                                                                    <span>{option}</span>
                                                                                </label>
                                                                            );
                                                                        })}
                                                                    </div>
                                                                )}

                                                                {question.type === 'multiple_choice' && (
                                                                    <div aria-labelledby={`${questionId}-label`} className="rsvp-choice-list">
                                                                        {question.options.map((option, optionIndex) => {
                                                                            const optionId = `${questionId}-${optionIndex}`;
                                                                            const checked = Array.isArray(answer) && answer.includes(option);
                                                                            return (
                                                                                <label htmlFor={optionId} key={`${question.id}-${option}`}>
                                                                                    <input
                                                                                        checked={checked}
                                                                                        className="form-check-input"
                                                                                        id={optionId}
                                                                                        onChange={(changeEvent) => toggleMultipleAnswer(guestIndex, question.id, option, changeEvent.target.checked)}
                                                                                        type="checkbox"
                                                                                    />
                                                                                    <span>{option}</span>
                                                                                </label>
                                                                            );
                                                                        })}
                                                                    </div>
                                                                )}

                                                                {question.type === 'boolean' && (
                                                                    <div aria-labelledby={`${questionId}-label`} className="rsvp-choice-list is-boolean" role="radiogroup">
                                                                        <label htmlFor={`${questionId}-yes`}>
                                                                            <input checked={answer === true} className="form-check-input" id={`${questionId}-yes`} name={questionId} onChange={() => setAnswer(guestIndex, question.id, true)} type="radio" />
                                                                            <span>Ja</span>
                                                                        </label>
                                                                        <label htmlFor={`${questionId}-no`}>
                                                                            <input checked={answer === false} className="form-check-input" id={`${questionId}-no`} name={questionId} onChange={() => setAnswer(guestIndex, question.id, false)} type="radio" />
                                                                            <span>Nein</span>
                                                                        </label>
                                                                        <button className="rsvp-clear-answer" disabled={answer === null || answer === undefined} onClick={() => setAnswer(guestIndex, question.id, null)} type="button">Auswahl aufheben</button>
                                                                    </div>
                                                                )}

                                                                {questionError && <div className="rsvp-field-error" role="alert">{questionError}</div>}
                                                            </fieldset>
                                                        );
                                                    })}
                                                    {fieldError(guestIndex, 'answers') && <div className="rsvp-field-error" role="alert">{fieldError(guestIndex, 'answers')}</div>}
                                                </div>
                                            )}

                                            <div className="rsvp-notes">
                                                <label htmlFor={`notes-${guest.invitedGuestId}`}>Persönliche Bemerkung <span>optional</span></label>
                                                <textarea
                                                    aria-invalid={Boolean(fieldError(guestIndex, 'notes'))}
                                                    className={`form-control${fieldError(guestIndex, 'notes') ? ' is-invalid' : ''}`}
                                                    id={`notes-${guest.invitedGuestId}`}
                                                    onChange={(changeEvent) => setResponse(guestIndex, { notes: changeEvent.target.value })}
                                                    placeholder="Was möchtet ihr uns noch mitteilen?"
                                                    rows={3}
                                                    value={response.notes}
                                                />
                                                {fieldError(guestIndex, 'notes') && <div className="invalid-feedback">{fieldError(guestIndex, 'notes')}</div>}
                                            </div>
                                        </fieldset>
                                    );
                                })}
                            </section>

                            <aside className="rsvp-summary" aria-labelledby="rsvp-summary-title">
                                <span className="rsvp-eyebrow">Eure Rückmeldung</span>
                                <h2 id="rsvp-summary-title">Aktueller Stand</h2>
                                <div className="rsvp-summary-counts" aria-live="polite">
                                    <div className="is-accepted"><strong>{acceptedCount}</strong><span>{acceptedCount === 1 ? 'Zusage' : 'Zusagen'}</span></div>
                                    <div className="is-declined"><strong>{declinedCount}</strong><span>{declinedCount === 1 ? 'Absage' : 'Absagen'}</span></div>
                                    <div className="is-pending"><strong>{pendingCount}</strong><span>Offen</span></div>
                                </div>
                                {responseDeadline && (
                                    <div className="rsvp-deadline">
                                        <span>Rückmeldung bitte bis</span>
                                        <strong>{formatDateTime(responseDeadline, wedding.timezone, false)}</strong>
                                    </div>
                                )}
                                <button className="rsvp-primary-button" disabled={form.processing || isLocked} type="submit">
                                    {form.processing ? <><span className="spinner-border spinner-border-sm" aria-hidden="true" /> Wird gespeichert …</> : isLocked ? 'Rückmeldung geschlossen' : 'Antworten speichern'}
                                </button>
                                {form.processing && <p className="rsvp-saving" role="status">Eure Antworten werden gespeichert.</p>}
                            </aside>
                        </div>
                    </form>
                )}
            </main>
        </>
    );
}
