import { Form, Head, Link, router, usePage } from '@inertiajs/react';
import { ArrowLeft, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import AppLayout from '@/layouts/app-layout';
import type { Auth } from '@/types';

type Reply = {
    id: number;
    body: string;
    created_at: string;
    user: { id: number; name: string };
};

type Discussion = {
    id: number;
    title: string;
    body: string;
    is_pinned: boolean;
    created_at: string;
    user: { id: number; name: string };
    lesson: { title: string } | null;
    replies: Reply[];
};

type Course = { id: number; title: string; slug: string };
type Props = { course: Course; discussion: Discussion };

function timeAgo(date: string) {
    const diff = Math.floor((Date.now() - new Date(date).getTime()) / 1000);
    if (diff < 60) return 'Baru saja';
    if (diff < 3600) return `${Math.floor(diff / 60)} mnt lalu`;
    if (diff < 86400) return `${Math.floor(diff / 3600)} jam lalu`;
    return `${Math.floor(diff / 86400)} hari lalu`;
}

export default function DiscussionShow({ course, discussion }: Props) {
    const { auth } = usePage<{ auth: Auth }>().props;

    function deleteDiscussion() {
        if (confirm('Hapus diskusi ini?')) {
            router.delete(`/courses/${course.slug}/discussions/${discussion.id}`);
        }
    }

    function deleteReply(replyId: number) {
        if (confirm('Hapus balasan ini?')) {
            router.delete(`/courses/${course.slug}/discussions/${discussion.id}/replies/${replyId}`);
        }
    }

    return (
        <>
            <Head title={discussion.title} />

            <div className="flex flex-col gap-6 p-4 md:p-6 max-w-3xl">
                <Link href={`/courses/${course.slug}/discussions`} className="flex items-center gap-1 text-sm text-primary hover:underline">
                    <ArrowLeft className="h-4 w-4" />
                    Kembali ke Diskusi
                </Link>

                {/* Main Post */}
                <div className="rounded-xl border bg-card p-5 shadow-sm">
                    <div className="flex items-start justify-between gap-3">
                        <div className="min-w-0">
                            <h1 className="text-xl font-bold">{discussion.title}</h1>
                            {discussion.lesson && (
                                <p className="mt-0.5 text-xs text-muted-foreground">Lesson: {discussion.lesson.title}</p>
                            )}
                        </div>
                        {(auth.user.id === discussion.user.id || auth.user.role === 'admin') && (
                            <button onClick={deleteDiscussion} className="shrink-0 rounded-md p-1.5 text-destructive hover:bg-destructive/10">
                                <Trash2 className="h-4 w-4" />
                            </button>
                        )}
                    </div>
                    <p className="mt-4 text-sm leading-relaxed whitespace-pre-wrap">{discussion.body}</p>
                    <div className="mt-4 flex items-center gap-2 text-xs text-muted-foreground">
                        <span className="font-medium">{discussion.user.name}</span>
                        <span>·</span>
                        <span>{timeAgo(discussion.created_at)}</span>
                    </div>
                </div>

                {/* Replies */}
                <div>
                    <h2 className="mb-3 font-semibold">{discussion.replies.length} Balasan</h2>

                    <div className="flex flex-col gap-3 mb-4">
                        {discussion.replies.map((reply) => (
                            <div key={reply.id} className="flex gap-3 rounded-xl border bg-card p-4">
                                <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm font-semibold">
                                    {reply.user.name[0].toUpperCase()}
                                </div>
                                <div className="flex-1 min-w-0">
                                    <div className="flex items-center justify-between gap-2">
                                        <div className="flex items-center gap-2 text-xs">
                                            <span className="font-medium">{reply.user.name}</span>
                                            <span className="text-muted-foreground">{timeAgo(reply.created_at)}</span>
                                        </div>
                                        {(auth.user.id === reply.user.id || auth.user.role === 'admin') && (
                                            <button onClick={() => deleteReply(reply.id)} className="rounded-md p-1 text-muted-foreground hover:text-destructive">
                                                <Trash2 className="h-3.5 w-3.5" />
                                            </button>
                                        )}
                                    </div>
                                    <p className="mt-1.5 text-sm leading-relaxed whitespace-pre-wrap">{reply.body}</p>
                                </div>
                            </div>
                        ))}
                    </div>

                    {/* Reply Form */}
                    <Form
                        action={`/courses/${course.slug}/discussions/${discussion.id}/replies`}
                        method="post"
                        resetOnSuccess
                        className="rounded-xl border bg-muted/20 p-4"
                    >
                        {({ processing, errors }) => (
                            <div className="flex flex-col gap-3">
                                <textarea
                                    name="body"
                                    rows={3}
                                    placeholder="Tulis balasan..."
                                    className="border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 flex w-full rounded-md border bg-transparent px-3 py-2 text-sm shadow-xs outline-none focus-visible:ring-[3px]"
                                    required
                                />
                                {errors.body && <p className="text-xs text-destructive">{errors.body}</p>}
                                <Button type="submit" disabled={processing} size="sm" className="self-start">
                                    Kirim Balasan
                                </Button>
                            </div>
                        )}
                    </Form>
                </div>
            </div>
        </>
    );
}

DiscussionShow.layout = (page: React.ReactNode) => <AppLayout breadcrumbs={[]}>{page}</AppLayout>;
