"use client"

import { useState } from "react"
import { useTranslations } from "next-intl"
import {
  Lock,
  MessageSquare,
  Pin,
  Plus,
  Trash2,
  Unlock,
  Flag,
  PinOff,
} from "lucide-react"

import {
  useForumTopics,
  useCreateTopic,
  useLockTopic,
  useUnlockTopic,
  usePinTopic,
  useUnpinTopic,
  useDeleteTopic,
  useOpenReportCount,
  type ForumTopic,
} from "@/services/forum"

export default function ForumPage() {
  const t = useTranslations("forum")
  const [showCreate, setShowCreate] = useState(false)
  const [title, setTitle] = useState("")
  const [content, setContent] = useState("")

  const { data: topicsData, isLoading } = useForumTopics()
  const { data: reportCount } = useOpenReportCount()
  const createTopic = useCreateTopic()
  const lockTopic = useLockTopic()
  const unlockTopic = useUnlockTopic()
  const pinTopic = usePinTopic()
  const unpinTopic = useUnpinTopic()
  const deleteTopic = useDeleteTopic()

  const topics: ForumTopic[] = topicsData?.content ?? []

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

  const handleDelete = (topicId: string) => {
    const reason = prompt(t("deleteReason"))
    if (reason !== null) {
      deleteTopic.mutate({ topicId, reason })
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">{t("title")}</h1>
          <p className="text-muted-foreground text-sm">{t("description")}</p>
        </div>
        <div className="flex items-center gap-3">
          {reportCount?.count > 0 && (
            <a
              href="/forum/reports"
              className="bg-destructive/10 text-destructive inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium"
            >
              <Flag className="h-4 w-4" />
              {reportCount.count} {t("openReports")}
            </a>
          )}
          <button
            onClick={() => setShowCreate(!showCreate)}
            className="bg-primary text-primary-foreground inline-flex items-center gap-2 rounded-md px-4 py-2 text-sm font-medium"
          >
            <Plus className="h-4 w-4" />
            {t("newTopic")}
          </button>
        </div>
      </div>

      {/* Create Topic Form */}
      {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>
      )}

      {/* Topic List */}
      {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) => (
            <div
              key={topic.id}
              className="bg-card flex items-center justify-between rounded-lg border p-4"
            >
              <div className="min-w-0 flex-1">
                <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" />
                  )}
                  <a
                    href={`/forum/${topic.id}`}
                    className="font-medium hover:underline truncate"
                  >
                    {topic.title}
                  </a>
                </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>
                  {topic.lastReplyAt && (
                    <span>
                      {t("lastReply")}:{" "}
                      {new Date(topic.lastReplyAt).toLocaleDateString("de-DE")}
                    </span>
                  )}
                </div>
              </div>

              {/* Moderation Actions */}
              <div className="flex items-center gap-1 ml-4">
                {topic.pinned ? (
                  <button
                    onClick={() => unpinTopic.mutate(topic.id)}
                    className="text-muted-foreground hover:text-foreground rounded p-1.5"
                    title={t("unpin")}
                  >
                    <PinOff className="h-4 w-4" />
                  </button>
                ) : (
                  <button
                    onClick={() => pinTopic.mutate(topic.id)}
                    className="text-muted-foreground hover:text-foreground rounded p-1.5"
                    title={t("pin")}
                  >
                    <Pin className="h-4 w-4" />
                  </button>
                )}
                {topic.locked ? (
                  <button
                    onClick={() => unlockTopic.mutate(topic.id)}
                    className="text-muted-foreground hover:text-foreground rounded p-1.5"
                    title={t("unlock")}
                  >
                    <Unlock className="h-4 w-4" />
                  </button>
                ) : (
                  <button
                    onClick={() => lockTopic.mutate(topic.id)}
                    className="text-muted-foreground hover:text-foreground rounded p-1.5"
                    title={t("lock")}
                  >
                    <Lock className="h-4 w-4" />
                  </button>
                )}
                <button
                  onClick={() => handleDelete(topic.id)}
                  className="text-muted-foreground hover:text-destructive rounded p-1.5"
                  title={t("delete")}
                >
                  <Trash2 className="h-4 w-4" />
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
