"use client"

import { useState } from "react"
import { useTranslations } from "next-intl"
import {
  Lock,
  MessageSquare,
  Pin,
  Plus,
  ThumbsUp,
  ThumbsDown,
  Flag,
  ArrowLeft,
} from "lucide-react"

import {
  usePortalForumTopics,
  usePortalForumTopic,
  usePortalForumReplies,
  usePortalCreateTopic,
  usePortalCreateReply,
  usePortalToggleReaction,
  usePortalReportContent,
  type ForumTopic,
  type ForumReply,
} from "@/services/forum"

export default function PortalForumPage() {
  const t = useTranslations("forum")
  const [selectedTopicId, setSelectedTopicId] = useState<string | null>(null)
  const [showCreate, setShowCreate] = useState(false)
  const [title, setTitle] = useState("")
  const [content, setContent] = useState("")
  const [replyContent, setReplyContent] = useState("")

  const { data: topicsData, isLoading } = usePortalForumTopics()
  const { data: topicDetail } = usePortalForumTopic(selectedTopicId ?? undefined)
  const { data: repliesData } = usePortalForumReplies(selectedTopicId ?? undefined)
  const createTopic = usePortalCreateTopic()
  const createReply = usePortalCreateReply(selectedTopicId ?? "")
  const toggleReaction = usePortalToggleReaction()
  const reportContent = usePortalReportContent()

  const topics: ForumTopic[] = topicsData?.content ?? []
  const replies: ForumReply[] = repliesData?.content ?? []

  const handleCreate = () => {
    if (!title.trim() || !content.trim()) return
    createTopic.mutate(
      { title: title.trim(), content: content.trim() },
      {
        onSuccess: () => {
          setTitle("")
          setContent("")
          setShowCreate(false)
        },
      }
    )
  }

  const handleReply = () => {
    if (!replyContent.trim() || !selectedTopicId) return
    createReply.mutate(
      { content: replyContent.trim() },
      {
        onSuccess: () => setReplyContent(""),
      }
    )
  }

  const handleReport = (targetType: "TOPIC" | "REPLY", targetId: string) => {
    const reason = prompt(t("reportReason"))
    if (reason) {
      reportContent.mutate({ targetType, targetId, reason })
    }
  }

  // Topic Detail View
  if (selectedTopicId && topicDetail) {
    return (
      <div className="space-y-4">
        <button
          onClick={() => setSelectedTopicId(null)}
          className="text-muted-foreground inline-flex items-center gap-1 text-sm hover:underline"
        >
          <ArrowLeft className="h-4 w-4" />
          {t("backToTopics")}
        </button>

        {/* Topic */}
        <div className="bg-card rounded-lg border p-4">
          <div className="flex items-center gap-2 mb-2">
            {topicDetail.pinned && <Pin className="text-primary h-4 w-4" />}
            {topicDetail.locked && <Lock className="text-muted-foreground h-4 w-4" />}
            <h2 className="text-lg font-bold">{topicDetail.title}</h2>
          </div>
          <div
            className="prose prose-sm dark:prose-invert mb-3"
            dangerouslySetInnerHTML={{ __html: topicDetail.content }}
          />
          <div className="flex items-center gap-3 text-xs text-muted-foreground">
            <span>{new Date(topicDetail.createdAt).toLocaleDateString("de-DE")}</span>
            <div className="flex items-center gap-2">
              <button
                onClick={() =>
                  toggleReaction.mutate({
                    targetType: "TOPIC",
                    targetId: topicDetail.id,
                    reactionType: "THUMBS_UP",
                  })
                }
                className="inline-flex items-center gap-1 rounded px-2 py-1 hover:bg-muted"
              >
                <ThumbsUp className="h-3 w-3" />
              </button>
              <button
                onClick={() =>
                  toggleReaction.mutate({
                    targetType: "TOPIC",
                    targetId: topicDetail.id,
                    reactionType: "THUMBS_DOWN",
                  })
                }
                className="inline-flex items-center gap-1 rounded px-2 py-1 hover:bg-muted"
              >
                <ThumbsDown className="h-3 w-3" />
              </button>
              <button
                onClick={() => handleReport("TOPIC", topicDetail.id)}
                className="inline-flex items-center gap-1 rounded px-2 py-1 hover:bg-muted text-muted-foreground"
              >
                <Flag className="h-3 w-3" />
              </button>
            </div>
          </div>
        </div>

        {/* Replies */}
        <div className="space-y-2">
          {replies.map((reply) => (
            <div key={reply.id} className="bg-card rounded-lg border p-3">
              <div
                className="prose prose-sm dark:prose-invert mb-2"
                dangerouslySetInnerHTML={{ __html: reply.content }}
              />
              <div className="flex items-center gap-3 text-xs text-muted-foreground">
                <span>{new Date(reply.createdAt).toLocaleDateString("de-DE")}</span>
                {reply.edited && <span className="italic">({t("edited")})</span>}
                <div className="flex items-center gap-1">
                  <button
                    onClick={() =>
                      toggleReaction.mutate({
                        targetType: "REPLY",
                        targetId: reply.id,
                        reactionType: "THUMBS_UP",
                      })
                    }
                    className="rounded px-1.5 py-0.5 hover:bg-muted"
                  >
                    <ThumbsUp className="h-3 w-3" />
                  </button>
                  <button
                    onClick={() =>
                      toggleReaction.mutate({
                        targetType: "REPLY",
                        targetId: reply.id,
                        reactionType: "THUMBS_DOWN",
                      })
                    }
                    className="rounded px-1.5 py-0.5 hover:bg-muted"
                  >
                    <ThumbsDown className="h-3 w-3" />
                  </button>
                  <button
                    onClick={() => handleReport("REPLY", reply.id)}
                    className="rounded px-1.5 py-0.5 hover:bg-muted"
                  >
                    <Flag className="h-3 w-3" />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Reply Form */}
        {!topicDetail.locked && (
          <div className="bg-card rounded-lg border p-3 space-y-2">
            <textarea
              value={replyContent}
              onChange={(e) => setReplyContent(e.target.value)}
              placeholder={t("replyPlaceholder")}
              rows={3}
              className="bg-background w-full rounded-md border px-3 py-2 text-sm"
            />
            <button
              onClick={handleReply}
              disabled={createReply.isPending || !replyContent.trim()}
              className="bg-primary text-primary-foreground rounded-md px-4 py-2 text-sm font-medium disabled:opacity-50"
            >
              {createReply.isPending ? t("sending") : t("reply")}
            </button>
          </div>
        )}
        {topicDetail.locked && (
          <div className="text-muted-foreground text-center text-sm py-4">
            <Lock className="h-4 w-4 inline mr-1" />
            {t("topicLocked")}
          </div>
        )}
      </div>
    )
  }

  // Topic List View
  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold">{t("title")}</h2>
        <button
          onClick={() => setShowCreate(!showCreate)}
          className="bg-primary text-primary-foreground inline-flex items-center gap-2 rounded-md px-3 py-1.5 text-sm font-medium"
        >
          <Plus className="h-4 w-4" />
          {t("newTopic")}
        </button>
      </div>

      {showCreate && (
        <div className="bg-card rounded-lg border p-4 space-y-3">
          <input
            type="text"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder={t("topicTitlePlaceholder")}
            className="bg-background w-full rounded-md border px-3 py-2 text-sm"
          />
          <textarea
            value={content}
            onChange={(e) => setContent(e.target.value)}
            placeholder={t("topicContentPlaceholder")}
            rows={4}
            className="bg-background w-full rounded-md border px-3 py-2 text-sm"
          />
          <div className="flex gap-2">
            <button
              onClick={handleCreate}
              disabled={createTopic.isPending}
              className="bg-primary text-primary-foreground rounded-md px-4 py-2 text-sm font-medium disabled:opacity-50"
            >
              {createTopic.isPending ? t("creating") : t("create")}
            </button>
            <button
              onClick={() => setShowCreate(false)}
              className="text-muted-foreground rounded-md px-4 py-2 text-sm"
            >
              {t("cancel")}
            </button>
          </div>
        </div>
      )}

      {isLoading ? (
        <div className="text-muted-foreground py-8 text-center text-sm">
          {t("loading")}
        </div>
      ) : topics.length === 0 ? (
        <div className="text-muted-foreground py-8 text-center text-sm">
          {t("noTopics")}
        </div>
      ) : (
        <div className="space-y-2">
          {topics.map((topic) => (
            <button
              key={topic.id}
              onClick={() => setSelectedTopicId(topic.id)}
              className="bg-card w-full text-left rounded-lg border p-4 hover:border-primary/50 transition-colors"
            >
              <div className="flex items-center gap-2">
                {topic.pinned && <Pin className="text-primary h-4 w-4 shrink-0" />}
                {topic.locked && <Lock className="text-muted-foreground h-4 w-4 shrink-0" />}
                <span className="font-medium truncate">{topic.title}</span>
              </div>
              <div className="text-muted-foreground mt-1 flex items-center gap-3 text-xs">
                <span className="inline-flex items-center gap-1">
                  <MessageSquare className="h-3 w-3" />
                  {topic.replyCount} {t("replies")}
                </span>
                <span>
                  {new Date(topic.createdAt).toLocaleDateString("de-DE")}
                </span>
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  )
}
