"use client"

import { useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { useTranslations } from "next-intl"
import { Pin } from "lucide-react"

import { Badge } from "@/shared/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { cn, formatDate } from "@/shared/lib/utils"
import { toggleAnnouncementPinAction } from "../actions"
import type { Announcement } from "../types"

export function AnnouncementCard({
  announcement,
  href,
  canManage,
}: {
  announcement: Announcement
  href?: string
  canManage?: boolean
}) {
  const t = useTranslations("announcements")
  const router = useRouter()
  const [isPinned, setIsPinned] = useState(announcement.isPinned)
  const [isToggling, setIsToggling] = useState(false)

  const handleTogglePin = async (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setIsToggling(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 {
      setIsToggling(false)
    }
  }

  const statusVariant: Record<Announcement["status"], "default" | "secondary" | "outline"> = {
    draft: "secondary",
    published: "default",
    archived: "outline",
  }

  const card = (
    <Card className={cn("h-full transition-colors hover:bg-accent/50", isPinned && "border-primary/50")}>
      <CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0">
        <CardTitle className="line-clamp-2 text-base">
          {isPinned ? (
            <Pin className="text-primary mr-1 inline h-3.5 w-3.5 fill-primary align-text-bottom" aria-hidden="true" />
          ) : null}
          {announcement.title}
        </CardTitle>
        <div className="flex shrink-0 items-center gap-1">
          {isPinned ? (
            <Badge variant="default" className="text-xs">
              {t("status.pinned")}
            </Badge>
          ) : null}
          <Badge variant={statusVariant[announcement.status]} className="text-xs">
            {t(`status.${announcement.status}`)}
          </Badge>
          {canManage ? (
            <button
              type="button"
              onClick={handleTogglePin}
              disabled={isToggling}
              aria-label={isPinned ? t("actions.unpin") : t("actions.pin")}
              className="text-muted-foreground hover:text-foreground inline-flex size-6 items-center justify-center rounded-md transition-colors hover:bg-accent disabled:opacity-50"
            >
              <Pin
                className={cn("h-3.5 w-3.5 transition-colors", isPinned && "fill-primary text-primary")}
              />
            </button>
          ) : null}
        </div>
      </CardHeader>
      <CardContent className="space-y-2">
        <p className="line-clamp-3 text-sm text-muted-foreground whitespace-pre-wrap">
          {announcement.content}
        </p>
        <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
          <Badge variant="outline" className="capitalize">
            {t(`type.${announcement.type}`)}
          </Badge>
          <span>
            {announcement.publishedAt
              ? t("meta.publishedAt", { date: formatDate(announcement.publishedAt) })
              : t("meta.updatedAt", { date: formatDate(announcement.updatedAt) })}
          </span>
          {announcement.authorName ? (
            <span className="ml-auto">{t("meta.author", { name: announcement.authorName })}</span>
          ) : null}
        </div>
      </CardContent>
    </Card>
  )

  if (href) {
    return (
      <Link href={href} className="block h-full" aria-label={announcement.title}>
        {card}
      </Link>
    )
  }

  return card
}
