"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { useTranslations } from "next-intl"
import {
  Archive,
  ArrowLeft,
  CheckCircle2,
  Megaphone,
  Pencil,
  Pin,
  Send,
  Trash2,
} from "lucide-react"

import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { ConfirmDeleteDialog } from "@/shared/components/ui/confirm-delete-dialog"
import { cn, formatDate } from "@/shared/lib/utils"

import {
  archiveAnnouncementAction,
  deleteAnnouncementAction,
  markAnnouncementAsReadAction,
  publishAnnouncementAction,
  toggleAnnouncementPinAction,
} from "../actions"
import type { Announcement } from "../types"

export function AnnouncementDetail({
  announcement,
  canManage,
  editHref,
  backHref,
}: {
  announcement: Announcement
  canManage?: boolean
  editHref?: string
  backHref?: string
}) {
  const t = useTranslations("announcements")
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)
  const [deleteOpen, setDeleteOpen] = useState(false)
  const [isPinned, setIsPinned] = useState(announcement.isPinned)
  const [isTogglingPin, setIsTogglingPin] = useState(false)
  const [isRead, setIsRead] = useState(announcement.isReadByCurrentUser ?? false)

  // 用户端自动标记已读（非管理端且未读时）
  useEffect(() => {
    if (canManage) return
    if (isRead) return

    let cancelled = false
    void markAnnouncementAsReadAction(announcement.id)
      .then((res) => {
        if (cancelled) return
        if (res.success) {
          setIsRead(true)
        }
      })
      .catch(() => {
        // 静默处理
      })

    return () => {
      cancelled = true
    }
  }, [canManage, isRead, announcement.id])

  const handlePublish = async () => {
    setIsWorking(true)
    try {
      const res = await publishAnnouncementAction(announcement.id)
      if (res.success) {
        toast.success(res.message)
        router.refresh()
      } else {
        toast.error(res.message || t("messages.publishFailed"))
      }
    } catch {
      toast.error(t("messages.publishFailed"))
    } finally {
      setIsWorking(false)
    }
  }

  const handleArchive = async () => {
    setIsWorking(true)
    try {
      const res = await archiveAnnouncementAction(announcement.id)
      if (res.success) {
        toast.success(res.message)
        router.refresh()
      } else {
        toast.error(res.message || t("messages.archiveFailed"))
      }
    } catch {
      toast.error(t("messages.archiveFailed"))
    } finally {
      setIsWorking(false)
    }
  }

  const handleDelete = async () => {
    setIsWorking(true)
    try {
      const res = await deleteAnnouncementAction(announcement.id)
      if (res.success) {
        toast.success(res.message)
        router.push("/admin/announcements")
        router.refresh()
      } else {
        toast.error(res.message || t("messages.deleteFailed"))
      }
    } catch {
      toast.error(t("messages.deleteFailed"))
    } finally {
      setIsWorking(false)
      setDeleteOpen(false)
    }
  }

  const handleTogglePin = async () => {
    setIsTogglingPin(true)
    const prevPinned = isPinned
    // 乐观更新
    setIsPinned(!prevPinned)
    try {
      const res = await toggleAnnouncementPinAction(announcement.id)
      if (res.success) {
        toast.success(t("messages.pinToggled"))
        router.refresh()
      } else {
        // 回滚
        setIsPinned(prevPinned)
        toast.error(res.message)
      }
    } catch {
      // 回滚
      setIsPinned(prevPinned)
      toast.error(t("messages.publishFailed"))
    } finally {
      setIsTogglingPin(false)
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-2">
        <div className="flex items-center gap-2">
          {backHref ? (
            <Button asChild variant="ghost" size="icon" aria-label={t("actions.back")}>
              <Link href={backHref}>
                <ArrowLeft className="h-4 w-4" />
              </Link>
            </Button>
          ) : null}
          <h2 className="text-2xl font-bold tracking-tight">{t("title.detail")}</h2>
        </div>
        {canManage ? (
          <div className="flex flex-wrap items-center gap-2">
            <Button onClick={handleTogglePin} disabled={isTogglingPin} variant="outline">
              <Pin className={cn("mr-2 h-4 w-4", isPinned && "fill-current")} />
              {isPinned ? t("actions.unpin") : t("actions.pin")}
            </Button>
            {announcement.status !== "published" ? (
              <Button onClick={handlePublish} disabled={isWorking} variant="outline">
                <Send className="mr-2 h-4 w-4" />
                {t("actions.publish")}
              </Button>
            ) : null}
            {announcement.status !== "archived" ? (
              <Button onClick={handleArchive} disabled={isWorking} variant="outline">
                <Archive className="mr-2 h-4 w-4" />
                {t("actions.archive")}
              </Button>
            ) : null}
            {editHref ? (
              <Button asChild>
                <Link href={editHref}>
                  <Pencil className="mr-2 h-4 w-4" />
                  {t("actions.edit")}
                </Link>
              </Button>
            ) : null}
            <Button
              onClick={() => setDeleteOpen(true)}
              disabled={isWorking}
              variant="destructive"
            >
              <Trash2 className="mr-2 h-4 w-4" />
              {t("actions.delete")}
            </Button>
          </div>
        ) : null}
      </div>

      <Card>
        <CardHeader className="space-y-2">
          <div className="flex flex-wrap items-center gap-2">
            <Badge variant="outline" className="capitalize">
              {t(`type.${announcement.type}`)}
            </Badge>
            <Badge className="capitalize">{t(`status.${announcement.status}`)}</Badge>
            {isPinned ? (
              <Badge variant="default" className="gap-1">
                <Pin className="h-3 w-3 fill-current" aria-hidden="true" />
                {t("status.pinned")}
              </Badge>
            ) : null}
            {/* 用户端：显示已读/未读状态 */}
            {!canManage ? (
              <Badge variant={isRead ? "secondary" : "default"} className="gap-1">
                {isRead ? (
                  <>
                    <CheckCircle2 className="h-3 w-3" aria-hidden="true" />
                    {t("status.read")}
                  </>
                ) : (
                  t("status.unread")
                )}
              </Badge>
            ) : null}
            {/* 管理端：显示已读人数 */}
            {canManage && announcement.readCount !== undefined ? (
              <span className="text-xs text-muted-foreground">
                {t("meta.readCount", { count: announcement.readCount })}
              </span>
            ) : null}
          </div>
          <CardTitle className="text-2xl">
            {isPinned ? (
              <Pin className="text-primary mr-1 inline h-5 w-5 fill-primary align-text-bottom" aria-hidden="true" />
            ) : null}
            {announcement.title}
          </CardTitle>
          <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
            <Megaphone className="h-3 w-3" />
            <span>
              {announcement.publishedAt
                ? t("meta.publishedAt", { date: formatDate(announcement.publishedAt) })
                : t("meta.createdAt", { date: formatDate(announcement.createdAt) })}
            </span>
            {announcement.authorName ? <span>{t("meta.author", { name: announcement.authorName })}</span> : null}
          </div>
        </CardHeader>
        <CardContent>
          <p className="whitespace-pre-wrap text-sm leading-relaxed">{announcement.content}</p>
        </CardContent>
      </Card>

      <ConfirmDeleteDialog
        open={deleteOpen}
        onOpenChange={setDeleteOpen}
        title={t("empty.deleteTitle")}
        description={t("empty.deleteDesc", { title: announcement.title })}
        onConfirm={handleDelete}
        isWorking={isWorking}
      />
    </div>
  )
}
