import { Head, Link, router, useForm, usePage } from '@inertiajs/react';
import PublicLayout from '@/Layouts/PublicLayout';
import Card from '@/Components/UI/Card';
import Badge from '@/Components/UI/Badge';
import Button from '@/Components/UI/Button';
import { PageProps } from '@/types';

interface PostRow {
    id: number;
    body: string;
    author_name: string;
    author_role: string;
    created_at: string;
    is_first_post: boolean;
    can_delete: boolean;
}

interface ThreadData {
    id: number;
    title: string;
    slug: string;
    is_pinned: boolean;
    is_locked: boolean;
    category: { id: number; name: string; slug: string; admin_only_posting: boolean };
    author_name: string;
}

const roleLabels: Record<string, string> = {
    super_admin: 'Super Administrator',
    academic_admin: 'Academic Administrator',
    facilitator: 'Facilitator',
    assessor: 'Assessor',
    support_officer: 'Support Officer',
    finance_officer: 'Finance Officer',
    student: 'Student',
};

export default function Thread({
    thread,
    posts,
    canReply,
    canModerate,
    canDeleteThread,
}: {
    thread: ThreadData;
    posts: PostRow[];
    canReply: boolean;
    canModerate: boolean;
    canDeleteThread: boolean;
}) {
    const { auth } = usePage<PageProps>().props;
    const { data, setData, post, processing, errors, reset } = useForm({ body: '' });

    const submitReply = (e: React.FormEvent) => {
        e.preventDefault();
        post(route('forum.posts.store', thread.slug), { onSuccess: () => reset('body') });
    };

    const deletePost = (postId: number) => {
        if (confirm('Delete this post?')) {
            router.delete(route('forum.posts.destroy', postId));
        }
    };

    const deleteThread = () => {
        if (confirm(`Delete the thread "${thread.title}"? This cannot be undone.`)) {
            router.delete(route('forum.threads.destroy', thread.slug));
        }
    };

    return (
        <PublicLayout>
            <Head title={thread.title} />

            <section className="mx-auto max-w-4xl px-6 pb-20 pt-16 lg:px-margin-page">
                <Link href={route('forum.category', thread.category.slug)} className="text-sm text-on-surface-variant hover:text-jgcp-navy">
                    &larr; {thread.category.name}
                </Link>

                <div className="mt-4 flex items-start justify-between gap-4">
                    <div>
                        <div className="flex items-center gap-2">
                            <h1 className="text-institute-title text-on-surface">{thread.title}</h1>
                            {thread.is_pinned && <Badge tone="gold">Pinned</Badge>}
                            {thread.is_locked && <Badge tone="archived">Locked</Badge>}
                        </div>
                        <p className="mt-1 text-sm text-on-surface-variant">Started by {thread.author_name}</p>
                    </div>

                    {(canModerate || canDeleteThread) && (
                        <div className="flex shrink-0 gap-2">
                            {canModerate && (
                                <>
                                    <Button
                                        variant="secondary"
                                        onClick={() => router.patch(route('forum.threads.pin', thread.slug))}
                                    >
                                        {thread.is_pinned ? 'Unpin' : 'Pin'}
                                    </Button>
                                    <Button
                                        variant="secondary"
                                        onClick={() => router.patch(route('forum.threads.lock', thread.slug))}
                                    >
                                        {thread.is_locked ? 'Unlock' : 'Lock'}
                                    </Button>
                                </>
                            )}
                            {canDeleteThread && (
                                <Button variant="ghost" className="!text-error" onClick={deleteThread}>
                                    Delete Thread
                                </Button>
                            )}
                        </div>
                    )}
                </div>

                <div className="mt-8 space-y-4">
                    {posts.map((p) => (
                        <Card key={p.id} className={p.is_first_post ? '!bg-surface-container-low' : ''}>
                            <div className="flex items-start justify-between gap-4">
                                <div>
                                    <p className="font-semibold text-on-surface">{p.author_name}</p>
                                    <p className="text-xs text-on-surface-variant">
                                        {roleLabels[p.author_role] ?? p.author_role} &middot; {p.created_at}
                                    </p>
                                </div>
                                {p.can_delete && (
                                    <button onClick={() => deletePost(p.id)} className="text-xs text-error hover:underline">
                                        Delete
                                    </button>
                                )}
                            </div>
                            <p className="mt-3 whitespace-pre-wrap text-sm text-on-surface">{p.body}</p>
                        </Card>
                    ))}
                </div>

                {thread.is_locked && (
                    <p className="mt-6 text-sm text-on-surface-variant">This thread is locked and no longer accepting replies.</p>
                )}

                {!thread.is_locked && !auth?.user && (
                    <p className="mt-6 text-sm text-on-surface-variant">
                        <Link href={route('login')} className="font-semibold text-jgcp-navy hover:underline">
                            Sign in
                        </Link>{' '}
                        to reply to this thread.
                    </p>
                )}

                {!thread.is_locked && auth?.user && !canReply && (
                    <p className="mt-6 text-sm text-on-surface-variant">Only administrators can post in this category.</p>
                )}

                {canReply && (
                    <Card className="mt-6">
                        <form onSubmit={submitReply} className="space-y-4">
                            <textarea
                                className="block w-full rounded border-outline-variant"
                                rows={5}
                                placeholder="Write a reply..."
                                value={data.body}
                                onChange={(e) => setData('body', e.target.value)}
                            />
                            {errors.body && <p className="text-sm text-error">{errors.body}</p>}
                            <Button type="submit" variant="primary" disabled={processing}>
                                Post Reply
                            </Button>
                        </form>
                    </Card>
                )}
            </section>
        </PublicLayout>
    );
}
