"use client"

import type { JSX } from "react"
import { AlertTriangle, Lock, Loader2, RefreshCw } from "lucide-react"
import { useTranslations } from "next-intl"
import { Button } from "@/shared/components/ui/button"
import { Alert, AlertDescription, AlertTitle } from "@/shared/components/ui/alert"
import type { DraftLockStatus } from "../data-access-drafts"

/**
 * P3-6 协同录入锁状态提示条。
 *
 * 三种状态：
 * 1. acquiring：获取中（loading）
 * 2. conflict：锁被他人持有（警告 + 重试按钮）
 * 3. acquired：已获取（轻量 tooltip 提示，不渲染 banner）
 */
interface DraftLockBannerProps {
  status: DraftLockStatus | null
  isAcquiring: boolean
  onRetry: () => void
}

export function DraftLockBanner({
  status,
  isAcquiring,
  onRetry,
}: DraftLockBannerProps): JSX.Element | null {
  const t = useTranslations("grades")

  // 获取中
  if (isAcquiring) {
    return (
      <Alert className="border-blue-200 bg-blue-50">
        <Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
        <AlertTitle className="text-blue-900">
          {t("collabLock.acquired")}
        </AlertTitle>
        <AlertDescription className="text-blue-700">
          {t("collabLock.lockInfoTooltip")}
        </AlertDescription>
      </Alert>
    )
  }

  // 无状态或自己持锁：不显示
  if (!status || status.isMine) return null

  // 锁被他人持有
  const teacherName = status.lockedByName ?? t("collabLock.lockConflictUnknownTeacher")

  return (
    <Alert className="border-destructive/50 text-destructive">
      <AlertTriangle className="h-4 w-4" aria-hidden="true" />
      <AlertTitle>
        <Lock className="inline h-3 w-3 mr-1" aria-hidden="true" />
        {t("collabLock.lockConflictTitle")}
      </AlertTitle>
      <AlertDescription className="flex items-center justify-between gap-4">
        <span>
          {t("collabLock.lockConflictDescription", { teacherName })}
        </span>
        <Button
          size="sm"
          variant="outline"
          onClick={onRetry}
        >
          <RefreshCw className="mr-2 h-3 w-3" aria-hidden="true" />
          {t("collabLock.retryAcquire")}
        </Button>
      </AlertDescription>
    </Alert>
  )
}
