"use client"

import { use } from "react"
import Link from "next/link"
import { useLocale } from "@/lib/i18n/context"
import { VoteButton } from "@/components/forum/vote-button"
import { CategoryBadge } from "@/components/forum/category-badge"
import { CommentItem } from "@/components/forum/comment-item"
import { CommentForm } from "@/components/forum/comment-form"
import { Button } from "@/components/ui/button"
import {
  getThreadById,
  getCommentsByThread,
  formatRelativeTime,
  type Comment,
} from "@/lib/mock-data"
import { Eye, MessageSquare, Pin, Lock, ArrowLeft } from "lucide-react"

function buildCommentTree(comments: Comment[]): { root: Comment; replies: Comment[] }[] {
  const rootComments = comments.filter((c) => !c.parent_id)
  return rootComments.map((root) => ({
    root,
    replies: comments.filter((c) => c.parent_id === root.id),
  }))
}

export default function ThreadDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params)
  const { locale, t } = useLocale()

  const thread = getThreadById(id)
  if (!thread) {
    return (
      <div className="flex flex-col items-center gap-4 py-20">
        <p className="text-muted-foreground">
          {locale === "tr" ? "Konu bulunamadi." : "Thread not found."}
        </p>
        <Link href="/">
          <Button variant="outline" size="sm">
            <ArrowLeft className="mr-1.5 h-4 w-4" />
            {t.common.back}
          </Button>
        </Link>
      </div>
    )
  }

  const comments = getCommentsByThread(id)
  const commentTree = buildCommentTree(comments)

  return (
    <div className="flex flex-col gap-6">
      {/* Back Button */}
      <Link href="/" className="self-start">
        <Button variant="ghost" size="sm" className="gap-1.5 text-muted-foreground">
          <ArrowLeft className="h-4 w-4" />
          {t.common.back}
        </Button>
      </Link>

      {/* Thread Content */}
      <article className="rounded-lg border border-border bg-card p-6">
        <div className="flex gap-4">
          {/* Vote */}
          <div className="hidden sm:block">
            <VoteButton initialCount={thread.vote_count} />
          </div>

          {/* Content */}
          <div className="flex min-w-0 flex-1 flex-col gap-4">
            {/* Badges */}
            <div className="flex flex-wrap items-center gap-2">
              {thread.is_pinned && (
                <span className="inline-flex items-center gap-1 rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
                  <Pin className="h-3 w-3" />
                  {t.forum.pinned}
                </span>
              )}
              {thread.is_locked && (
                <span className="inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground">
                  <Lock className="h-3 w-3" />
                  {t.forum.locked}
                </span>
              )}
              <CategoryBadge category={thread.category} />
            </div>

            {/* Title */}
            <h1 className="text-xl font-bold leading-tight text-foreground text-balance">
              {thread.title}
            </h1>

            {/* Meta */}
            <div className="flex flex-wrap items-center gap-3 text-sm text-muted-foreground">
              <Link
                href={`/profile/${thread.author.username}`}
                className="font-medium text-foreground/80 hover:text-primary transition-colors"
              >
                {thread.author.display_name}
              </Link>
              <span>{formatRelativeTime(thread.created_at, locale)}</span>
              <span className="flex items-center gap-1">
                <Eye className="h-3.5 w-3.5" />
                {thread.view_count} {t.forum.views}
              </span>
              <span className="flex items-center gap-1">
                <MessageSquare className="h-3.5 w-3.5" />
                {thread.comment_count} {t.forum.comments}
              </span>
            </div>

            {/* Body */}
            <div className="text-sm leading-relaxed text-foreground/90 whitespace-pre-line">
              {thread.content}
            </div>

            {/* Mobile Vote */}
            <div className="sm:hidden">
              <VoteButton initialCount={thread.vote_count} orientation="horizontal" />
            </div>
          </div>
        </div>
      </article>

      {/* Comments Section */}
      <div className="rounded-lg border border-border bg-card p-6">
        <h2 className="mb-4 text-base font-semibold text-foreground">
          {t.forum.comments} ({comments.length})
        </h2>

        {/* Comment Form */}
        <div className="mb-6">
          <CommentForm threadId={id} />
        </div>

        {/* Comment List */}
        {commentTree.length > 0 ? (
          <div className="flex flex-col divide-y divide-border">
            {commentTree.map(({ root, replies }) => (
              <CommentItem key={root.id} comment={root} replies={replies} />
            ))}
          </div>
        ) : (
          <p className="py-8 text-center text-sm text-muted-foreground">
            {locale === "tr" ? "Henuz yorum yok. Ilk yorumu siz yapin!" : "No comments yet. Be the first to comment!"}
          </p>
        )}
      </div>
    </div>
  )
}
