"use client"

import { useMemo } from "react"
import Link from "next/link"
import { ChevronLeft, ChevronRight } from "lucide-react"
import { useTranslations } from "next-intl"

import { Button } from "@/shared/components/ui/button"
import { cn } from "@/shared/lib/utils"

/**
 * P2-6: 公告列表分页组件。
 *
 * 通过 URL `?page=N` 持久化当前页码（RSC 重新渲染模式，与 AnnouncementList 的
 * `?status=` 过滤机制一致），不引入客户端路由状态。
 *
 * 设计要点：
 * - 服务端渲染友好：仅渲染 a 链接，无 onClick 路由副作用
 * - a11y：上一页/下一页按钮使用 aria-label，当前页用 aria-current="page"
 * - 边界处理：total=0 时不渲染分页；首页时上一页禁用；末页时下一页禁用
 * - 计算窗口：当总页数 > 7 时显示首末页 + 当前页 ±1 + 省略号，避免溢出
 *
 * v3: 不再接收 `buildHref` 函数 prop（Server Component 不能传函数给 Client Component）。
 * 改为接收 `basePath` + `statusFilter`，在客户端自行构建分页 URL。
 */
export function AnnouncementPagination({
  page,
  pageSize,
  total,
  basePath,
  statusFilter,
  className,
}: {
  page: number
  pageSize: number
  total: number
  basePath: string
  statusFilter?: string
  className?: string
}) {
  const t = useTranslations("announcements")

  const totalPages = Math.max(1, Math.ceil(total / pageSize))
  const currentPage = Math.min(Math.max(1, page), totalPages)

  // 客户端构建分页 URL：保留 ?status= 过滤参数
  const buildHref = (targetPage: number): string => {
    const params = new URLSearchParams()
    if (statusFilter && statusFilter !== "all") params.set("status", statusFilter)
    if (targetPage > 1) params.set("page", String(targetPage))
    const qs = params.toString()
    return qs ? `${basePath}?${qs}` : basePath
  }

  const pages = useMemo(() => {
    if (totalPages <= 7) {
      return Array.from({ length: totalPages }, (_, i) => i + 1)
    }
    // 窗口策略：首末页 + 当前页 ±1 + 省略号占位
    const result: (number | "...")[] = [1]
    const start = Math.max(2, currentPage - 1)
    const end = Math.min(totalPages - 1, currentPage + 1)
    if (start > 2) result.push("...")
    for (let i = start; i <= end; i++) result.push(i)
    if (end < totalPages - 1) result.push("...")
    result.push(totalPages)
    return result
  }, [currentPage, totalPages])

  if (total === 0) return null
  const isFirst = currentPage === 1
  const isLast = currentPage === totalPages

  return (
    <nav
      aria-label={t("pagination.label")}
      className={cn("flex items-center justify-center gap-1", className)}
    >
      <Button
        variant="outline"
        size="icon"
        asChild
        aria-disabled={isFirst}
        aria-label={t("pagination.prev")}
        className={cn(isFirst && "pointer-events-none opacity-50")}
      >
        <Link href={buildHref(Math.max(1, currentPage - 1))} aria-disabled={isFirst}>
          <ChevronLeft className="h-4 w-4" />
        </Link>
      </Button>

      {pages.map((p, idx) =>
        p === "..." ? (
          <span
            key={`ellipsis-${idx}`}
            className="px-2 text-muted-foreground"
            aria-hidden="true"
          >
            …
          </span>
        ) : (
          <Button
            key={p}
            variant={p === currentPage ? "default" : "outline"}
            size="icon"
            asChild
            aria-current={p === currentPage ? "page" : undefined}
            aria-label={t("pagination.page", { page: p })}
            className={cn("min-w-[2.5rem]", p === currentPage && "pointer-events-none")}
          >
            <Link href={buildHref(p)}>{p}</Link>
          </Button>
        )
      )}

      <Button
        variant="outline"
        size="icon"
        asChild
        aria-disabled={isLast}
        aria-label={t("pagination.next")}
        className={cn(isLast && "pointer-events-none opacity-50")}
      >
        <Link href={buildHref(Math.min(totalPages, currentPage + 1))} aria-disabled={isLast}>
          <ChevronRight className="h-4 w-4" />
        </Link>
      </Button>
    </nav>
  )
}
