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

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

type GuestFeedComment = {
    id: string;
    authorName: string;
    body: string;
    createdAt: string;
    updatedAt: string;
    canEdit: boolean;
    canDelete: boolean;
};

type GuestFeedPost = {
    id: string;
    eventId: string;
    eventTitle: string;
    authorName: string;
    body: string;
    createdAt: string;
    updatedAt: string;
    canEdit: boolean;
    canDelete: boolean;
    comments: GuestFeedComment[];
};

type GuestFeedPageProps = {
    wedding: { name: string; timezone: string };
    events: GuestFeedEvent[];
    posts: GuestFeedPost[];
    pagination: {
        currentPage: number;
        lastPage: number;
        previousPageUrl: string | null;
        nextPageUrl: string | null;
    };
    permissions: { canPost: boolean };
    flash: { success: string | null };
    errors: Record<string, string>;
};

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);
    }
};

const wasEdited = (createdAt: string, updatedAt: string) => {
    const created = new Date(createdAt).getTime();
    const updated = new Date(updatedAt).getTime();
    return Number.isFinite(created) && Number.isFinite(updated) && updated > created;
};

export default function GuestFeedIndex() {
    const { wedding, events, posts, pagination, permissions, flash, errors } = usePage<GuestFeedPageProps>().props;
    const postForm = useForm({ event_id: events[0]?.id ?? '', body: '' });
    const [eventFilter, setEventFilter] = useState('all');
    const [editingPostId, setEditingPostId] = useState<string | null>(null);
    const [editingPostBody, setEditingPostBody] = useState('');
    const [commentDrafts, setCommentDrafts] = useState<Record<string, string>>({});
    const [editingCommentId, setEditingCommentId] = useState<string | null>(null);
    const [editingCommentBody, setEditingCommentBody] = useState('');
    const [pendingAction, setPendingAction] = useState<string | null>(null);
    const [mutationErrorOwner, setMutationErrorOwner] = useState<string | null>(null);
    const postEditRef = useRef<HTMLTextAreaElement>(null);
    const commentEditRef = useRef<HTMLTextAreaElement>(null);

    const sortedPosts = useMemo(() => [...posts]
        .filter((post) => eventFilter === 'all' || post.eventId === eventFilter)
        .sort((left, right) => new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime()), [eventFilter, posts]);
    const hasDraftComment = Object.values(commentDrafts).some((body) => body.trim().length > 0);
    const originalEditingPost = posts.find((post) => post.id === editingPostId);
    const originalEditingComment = posts.flatMap((post) => post.comments).find((comment) => comment.id === editingCommentId);
    const hasUnsavedChanges = postForm.data.body.trim().length > 0
        || postForm.data.event_id !== (events[0]?.id ?? '')
        || (originalEditingPost !== undefined && editingPostBody !== originalEditingPost.body)
        || (originalEditingComment !== undefined && editingCommentBody !== originalEditingComment.body)
        || hasDraftComment;
    const generalError = errors.guest_feed ?? errors.feed ?? errors.general;
    const mutationBodyError = errors.body ?? Object.entries(errors).find(([key]) => key.endsWith('.body'))?.[1];

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

    const submitPost = (submitEvent: FormEvent<HTMLFormElement>) => {
        submitEvent.preventDefault();
        if (postForm.processing || !permissions.canPost || events.length === 0) return;
        postForm.post('/gaestefeed/beitraege', {
            preserveScroll: true,
            onSuccess: () => postForm.reset('body'),
        });
    };

    const startPostEdit = (post: GuestFeedPost) => {
        setEditingCommentId(null);
        setEditingPostId(post.id);
        setEditingPostBody(post.body);
        setMutationErrorOwner(null);
        window.setTimeout(() => postEditRef.current?.focus(), 100);
    };

    const savePostEdit = (postId: string) => {
        if (pendingAction || editingPostBody.length > 2000) return;
        const owner = `post-${postId}`;
        setPendingAction(owner);
        setMutationErrorOwner(owner);
        router.put(`/gaestefeed/beitraege/${postId}`, { body: editingPostBody }, {
            preserveScroll: true,
            onSuccess: () => { setEditingPostId(null); setMutationErrorOwner(null); },
            onFinish: () => setPendingAction(null),
        });
    };

    const deletePost = (post: GuestFeedPost) => {
        if (pendingAction || !window.confirm('Möchtest du diesen Beitrag wirklich löschen? Die Antworten werden möglicherweise ebenfalls entfernt.')) return;
        const action = `delete-post-${post.id}`;
        setPendingAction(action);
        router.delete(`/gaestefeed/beitraege/${post.id}`, {
            preserveScroll: true,
            onSuccess: () => { if (editingPostId === post.id) setEditingPostId(null); },
            onFinish: () => setPendingAction(null),
        });
    };

    const submitComment = (postId: string) => {
        const body = commentDrafts[postId] ?? '';
        if (pendingAction || !permissions.canPost || body.length > 1000) return;
        const owner = `comment-new-${postId}`;
        setPendingAction(owner);
        setMutationErrorOwner(owner);
        router.post(`/gaestefeed/beitraege/${postId}/antworten`, { body }, {
            preserveScroll: true,
            onSuccess: () => { setCommentDrafts((drafts) => ({ ...drafts, [postId]: '' })); setMutationErrorOwner(null); },
            onFinish: () => setPendingAction(null),
        });
    };

    const startCommentEdit = (comment: GuestFeedComment) => {
        setEditingPostId(null);
        setEditingCommentId(comment.id);
        setEditingCommentBody(comment.body);
        setMutationErrorOwner(null);
        window.setTimeout(() => commentEditRef.current?.focus(), 100);
    };

    const saveCommentEdit = (commentId: string) => {
        if (pendingAction || editingCommentBody.length > 1000) return;
        const owner = `comment-${commentId}`;
        setPendingAction(owner);
        setMutationErrorOwner(owner);
        router.put(`/gaestefeed/antworten/${commentId}`, { body: editingCommentBody }, {
            preserveScroll: true,
            onSuccess: () => { setEditingCommentId(null); setMutationErrorOwner(null); },
            onFinish: () => setPendingAction(null),
        });
    };

    const deleteComment = (comment: GuestFeedComment) => {
        if (pendingAction || !window.confirm('Möchtest du diese Antwort wirklich löschen?')) return;
        const action = `delete-comment-${comment.id}`;
        setPendingAction(action);
        router.delete(`/gaestefeed/antworten/${comment.id}`, {
            preserveScroll: true,
            onSuccess: () => { if (editingCommentId === comment.id) setEditingCommentId(null); },
            onFinish: () => setPendingAction(null),
        });
    };

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

    return (
        <>
            <Head title="Privater Gästefeed" />
            <main className="guest-feed-shell">
                <nav className="guest-feed-nav" aria-label="Bereichsnavigation"><div><span className="guest-feed-eyebrow">{wedding.name}</span><strong>Privater Gästefeed</strong></div><Link className="guest-feed-secondary" href="/dashboard" onClick={handleBack}>Zurück zum Dashboard</Link></nav>
                <header className="guest-feed-header"><span className="guest-feed-eyebrow">Unter Gästen</span><h1>Ideen teilen, gemeinsam planen.</h1><p>Dieser private Bereich ist für eingeladene Gäste und Helfer bestimmt. Beiträge und Antworten erscheinen unter eurem gemeinsamen Kontonamen.</p></header>

                {flash.success && <div className="alert guest-feed-success" role="status">{flash.success}</div>}{generalError && <div className="alert alert-danger guest-feed-page-error" role="alert">{generalError}</div>}
                {events.length === 0 && <section className="guest-feed-no-events" role="status"><span aria-hidden="true">◇</span><div><h2>Momentan ist kein Gästefeed verfügbar</h2><p>Du bist derzeit keiner veröffentlichten Veranstaltung mit aktivem Gästefeed zugeordnet.</p></div></section>}

                {permissions.canPost && events.length > 0 && <section className="guest-feed-composer" aria-labelledby="guest-feed-composer-title"><div><span className="guest-feed-eyebrow">Neuer Beitrag</span><h2 id="guest-feed-composer-title">Was möchtet ihr teilen?</h2></div><form aria-busy={postForm.processing} noValidate onSubmit={submitPost}><div className="guest-feed-composer-grid"><div><label htmlFor="guest-feed-event">Veranstaltung</label><select className={`form-select${postForm.errors.event_id ? ' is-invalid' : ''}`} id="guest-feed-event" onChange={(event) => postForm.setData('event_id', event.target.value)} value={postForm.data.event_id}>{events.map((event) => <option key={event.id} value={event.id}>{event.title} · {formatDateTime(event.startsAt, wedding.timezone)}</option>)}</select>{postForm.errors.event_id && <div className="invalid-feedback">{postForm.errors.event_id}</div>}</div><div><label htmlFor="guest-feed-body">Beitrag</label><textarea className={`form-control${postForm.errors.body ? ' is-invalid' : ''}`} id="guest-feed-body" maxLength={2000} onChange={(event) => postForm.setData('body', event.target.value)} placeholder="Geschenkidee, Fahrgemeinschaft oder Überraschungsplanung …" rows={5} value={postForm.data.body} /><div className="guest-feed-character-count"><span>Klartext, sichtbar für berechtigte Gäste</span><span>{postForm.data.body.length}/2.000</span></div>{postForm.errors.body && <div className="invalid-feedback">{postForm.errors.body}</div>}</div></div><button className="guest-feed-primary" disabled={postForm.processing} type="submit">{postForm.processing ? <><span className="spinner-border spinner-border-sm" aria-hidden="true" /> Wird veröffentlicht …</> : 'Beitrag veröffentlichen'}</button></form></section>}

                <div className="guest-feed-content-heading"><div><span className="guest-feed-eyebrow">Aktuelle Beiträge</span><h2>Gespräche</h2></div>{permissions.canPost && events.length > 1 && <div><label htmlFor="guest-feed-filter">Nach Veranstaltung filtern</label><select className="form-select" id="guest-feed-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>

                {posts.length === 0 ? <section className="guest-feed-empty"><span aria-hidden="true">◇</span><h2>Noch keine Beiträge</h2><p>Wenn Gäste etwas teilen, beginnt hier euer privater Austausch.</p></section> : sortedPosts.length === 0 ? <section className="guest-feed-empty"><h2>Keine Beiträge zu dieser Veranstaltung</h2><p>Wähle eine andere Veranstaltung oder zeige alle Beiträge.</p></section> : <section className="guest-feed-list" aria-label="Beiträge im privaten Gästefeed">{sortedPosts.map((post) => {
                    const postErrorOwner = `post-${post.id}`;
                    return <article className="guest-feed-post" key={post.id}><header><div className="guest-feed-avatar" aria-hidden="true">{post.authorName.trim().charAt(0).toLocaleUpperCase('de-DE') || '◇'}</div><div><strong>{post.authorName}</strong><span>{post.eventTitle}</span></div><div><time dateTime={post.createdAt}>{formatDateTime(post.createdAt, wedding.timezone)}</time>{wasEdited(post.createdAt, post.updatedAt) && <small>Bearbeitet</small>}</div></header>
                        {editingPostId === post.id && permissions.canPost ? <div className="guest-feed-edit-area"><label htmlFor={`guest-feed-edit-${post.id}`}>Beitrag bearbeiten</label><textarea id={`guest-feed-edit-${post.id}`} maxLength={2000} onChange={(event) => setEditingPostBody(event.target.value)} ref={postEditRef} rows={5} value={editingPostBody} /><div className="guest-feed-character-count"><span>{editingPostBody.length}/2.000</span></div>{mutationErrorOwner === postErrorOwner && mutationBodyError && <p className="guest-feed-field-error">{mutationBodyError}</p>}<div><button className="guest-feed-text-button" disabled={pendingAction !== null} onClick={() => setEditingPostId(null)} type="button">Abbrechen</button><button className="guest-feed-primary" disabled={pendingAction !== null} onClick={() => savePostEdit(post.id)} type="button">{pendingAction === postErrorOwner ? 'Wird gespeichert …' : 'Speichern'}</button></div></div> : <p className="guest-feed-post-body">{post.body}</p>}
                        <div className="guest-feed-post-actions">{permissions.canPost && post.canEdit && editingPostId !== post.id && <button className="guest-feed-text-button" disabled={pendingAction !== null} onClick={() => startPostEdit(post)} type="button">Bearbeiten</button>}{post.canDelete && <button className="guest-feed-text-button is-danger" disabled={pendingAction !== null} onClick={() => deletePost(post)} type="button">{pendingAction === `delete-post-${post.id}` ? 'Wird gelöscht …' : 'Löschen'}</button>}</div>

                        <section className="guest-feed-comments" aria-labelledby={`guest-feed-comments-${post.id}`}><h3 id={`guest-feed-comments-${post.id}`}>{post.comments.length} {post.comments.length === 1 ? 'Antwort' : 'Antworten'}</h3>{post.comments.length > 0 && <ol>{post.comments.map((comment) => {
                            const commentErrorOwner = `comment-${comment.id}`;
                            return <li key={comment.id}><div className="guest-feed-comment-heading"><div><strong>{comment.authorName}</strong><time dateTime={comment.createdAt}>{formatDateTime(comment.createdAt, wedding.timezone)}</time>{wasEdited(comment.createdAt, comment.updatedAt) && <small>Bearbeitet</small>}</div><div>{permissions.canPost && comment.canEdit && editingCommentId !== comment.id && <button className="guest-feed-text-button" disabled={pendingAction !== null} onClick={() => startCommentEdit(comment)} type="button">Bearbeiten</button>}{comment.canDelete && <button className="guest-feed-text-button is-danger" disabled={pendingAction !== null} onClick={() => deleteComment(comment)} type="button">{pendingAction === `delete-comment-${comment.id}` ? 'Wird gelöscht …' : 'Löschen'}</button>}</div></div>{editingCommentId === comment.id && permissions.canPost ? <div className="guest-feed-edit-area is-comment"><label htmlFor={`guest-feed-comment-edit-${comment.id}`}>Antwort bearbeiten</label><textarea id={`guest-feed-comment-edit-${comment.id}`} maxLength={1000} onChange={(event) => setEditingCommentBody(event.target.value)} ref={commentEditRef} rows={3} value={editingCommentBody} /><div className="guest-feed-character-count"><span>{editingCommentBody.length}/1.000</span></div>{mutationErrorOwner === commentErrorOwner && mutationBodyError && <p className="guest-feed-field-error">{mutationBodyError}</p>}<div><button className="guest-feed-text-button" disabled={pendingAction !== null} onClick={() => setEditingCommentId(null)} type="button">Abbrechen</button><button className="guest-feed-primary" disabled={pendingAction !== null} onClick={() => saveCommentEdit(comment.id)} type="button">{pendingAction === commentErrorOwner ? 'Wird gespeichert …' : 'Speichern'}</button></div></div> : <p>{comment.body}</p>}</li>;
                        })}</ol>}{permissions.canPost && <div className="guest-feed-reply"><label htmlFor={`guest-feed-reply-${post.id}`}>Antwort schreiben</label><textarea id={`guest-feed-reply-${post.id}`} maxLength={1000} onChange={(event) => setCommentDrafts((drafts) => ({ ...drafts, [post.id]: event.target.value }))} placeholder="Eure Antwort …" rows={3} value={commentDrafts[post.id] ?? ''} /><div className="guest-feed-character-count"><span>{(commentDrafts[post.id] ?? '').length}/1.000</span></div>{mutationErrorOwner === `comment-new-${post.id}` && mutationBodyError && <p className="guest-feed-field-error">{mutationBodyError}</p>}<button className="guest-feed-secondary" disabled={pendingAction !== null} onClick={() => submitComment(post.id)} type="button">{pendingAction === `comment-new-${post.id}` ? 'Wird gesendet …' : 'Antwort senden'}</button></div>}</section>
                    </article>;
                })}</section>}

                {pagination.lastPage > 1 && <nav className="guest-feed-pagination" aria-label="Seitennavigation"><span>Seite {pagination.currentPage} von {pagination.lastPage}</span><div>{pagination.previousPageUrl ? <Link className="guest-feed-secondary" href={pagination.previousPageUrl} preserveScroll>Vorherige Seite</Link> : <span className="guest-feed-disabled-link">Vorherige Seite</span>}{pagination.nextPageUrl ? <Link className="guest-feed-secondary" href={pagination.nextPageUrl} preserveScroll>Nächste Seite</Link> : <span className="guest-feed-disabled-link">Nächste Seite</span>}</div></nav>}
            </main>
        </>
    );
}
