"use client"

import { useState } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { useCallback } from "react"
import { useTranslations } from "next-intl"
import { toast } from "sonner"
import { FileText, Trash2, Send, Download } from "lucide-react"

import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Label } from "@/shared/components/ui/label"
import { EmptyState } from "@/shared/components/ui/empty-state"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/components/ui/select"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/components/ui/dialog"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/shared/components/ui/tooltip"
import { formatDate } from "@/shared/lib/utils"
import { usePermission } from "@/shared/hooks"
import { Permissions } from "@/shared/types/permissions"
import { useDiagnosticService } from "../services/diagnostic-service-context"
import type { DiagnosticReportWithDetails } from "../types"
import {
  getConfidenceLevel,
  confidenceBadgeVariant,
  type ConfidenceLevel,
} from "./confidence-utils"

const statusColors: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
  draft: "secondary",
  published: "default",
  archived: "outline",
}

interface ReportListProps {
  reports: DiagnosticReportWithDetails[]
}

export function ReportList({ reports }: ReportListProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { hasPermission } = usePermission()
  const t = useTranslations("diagnostic")
  const canManage = hasPermission(Permissions.DIAGNOSTIC_MANAGE)
  // v2-P1-4: 通过 Context 注入服务，不直接 import actions
  const service = useDiagnosticService()

  const [deleteId, setDeleteId] = useState<string | null>(null)
  const [publishId, setPublishId] = useState<string | null>(null)
  const [isBusy, setIsBusy] = useState(false)

  const updateParam = useCallback(
    (key: string, value: string) => {
      const params = new URLSearchParams(searchParams.toString())
      if (value && value !== "all") {
        params.set(key, value)
      } else {
        params.delete(key)
      }
      router.push(`?${params.toString()}`)
    },
    [router, searchParams]
  )

  const handlePublish = async () => {
    if (!publishId) return
    setIsBusy(true)
    const result = await service.publishReport(publishId)
    setIsBusy(false)
    if (result.success) {
      toast.success(result.message)
      setPublishId(null)
      router.refresh()
    } else {
      toast.error(result.message || t("error.publishFailed"))
    }
  }

  const handleDelete = async () => {
    if (!deleteId) return
    setIsBusy(true)
    const result = await service.deleteReport(deleteId)
    setIsBusy(false)
    if (result.success) {
      toast.success(result.message)
      setDeleteId(null)
      router.refresh()
    } else {
      toast.error(result.message || t("error.deleteFailed"))
    }
  }

  /**
   * v3-P2-4: 导出诊断报告为 Excel。
   * 调用 server action 获取 base64 buffer，前端转 Blob 下载。
   */
  const handleExport = async (reportId: string) => {
    setIsBusy(true)
    try {
      const result = await service.exportReport(reportId)
      if (!result.success || !result.data) {
        toast.error(result.message || t("error.exportFailed"))
        return
      }
      // base64 -> Blob -> 下载
      const binaryString = atob(result.data.buffer)
      const bytes = new Uint8Array(binaryString.length)
      for (let i = 0; i < binaryString.length; i += 1) {
        bytes[i] = binaryString.charCodeAt(i)
      }
      const blob = new Blob([bytes], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      })
      const url = URL.createObjectURL(blob)
      const a = document.createElement("a")
      a.href = url
      a.download = result.data.filename
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      toast.success(t("reportList.exportSuccess"))
    } catch {
      toast.error(t("error.exportFailed"))
    } finally {
      setIsBusy(false)
    }
  }

  // v4-P3-7: 置信度标签与提示
  const confidenceLabel = (level: ConfidenceLevel): string => {
    if (level === "high") return t("reportList.confidenceHigh")
    if (level === "medium") return t("reportList.confidenceMedium")
    if (level === "low") return t("reportList.confidenceLow")
    return t("reportList.confidenceInsufficient")
  }

  const confidenceHint = (level: ConfidenceLevel): string => {
    if (level === "high") return t("reportList.confidenceHighHint")
    if (level === "medium") return t("reportList.confidenceMediumHint")
    if (level === "low") return t("reportList.confidenceLowHint")
    return t("reportList.confidenceInsufficient")
  }

  const reportType = searchParams.get("reportType") ?? "all"
  const status = searchParams.get("status") ?? "all"

  const typeLabel = (reportType: string): string => {
    if (reportType === "individual") return t("type.individual")
    if (reportType === "class") return t("type.class")
    if (reportType === "grade") return t("type.grade")
    return reportType
  }

  const statusLabel = (status: string): string => {
    if (status === "draft") return t("status.draft")
    if (status === "published") return t("status.published")
    if (status === "archived") return t("status.archived")
    return status
  }

  const studentTargetDisplay = (r: DiagnosticReportWithDetails): string => {
    if (r.studentName) return r.studentName
    if (r.reportType === "class") return t("reportList.classReportPlaceholder")
    if (r.reportType === "grade") return t("reportList.gradeReportPlaceholder")
    return "-"
  }

  return (
    <div className="space-y-4">
      {/* 过滤器 */}
      <div className="grid grid-cols-1 gap-4 rounded-lg border bg-card p-4 md:grid-cols-2">
        <div className="grid gap-2">
          <Label htmlFor="filter-report-type" className="text-xs">{t("filters.reportType")}</Label>
          <Select value={reportType} onValueChange={(v) => updateParam("reportType", v)}>
            <SelectTrigger id="filter-report-type" className="h-9">
              <SelectValue placeholder={t("filters.allTypes")} />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">{t("filters.allTypes")}</SelectItem>
              <SelectItem value="individual">{t("type.individual")}</SelectItem>
              <SelectItem value="class">{t("type.class")}</SelectItem>
              <SelectItem value="grade">{t("type.grade")}</SelectItem>
            </SelectContent>
          </Select>
        </div>
        <div className="grid gap-2">
          <Label htmlFor="filter-report-status" className="text-xs">{t("filters.status")}</Label>
          <Select value={status} onValueChange={(v) => updateParam("status", v)}>
            <SelectTrigger id="filter-report-status" className="h-9">
              <SelectValue placeholder={t("filters.allStatuses")} />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">{t("filters.allStatuses")}</SelectItem>
              <SelectItem value="draft">{t("status.draft")}</SelectItem>
              <SelectItem value="published">{t("status.published")}</SelectItem>
              <SelectItem value="archived">{t("status.archived")}</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {reports.length === 0 ? (
        <EmptyState
          title={t("empty.noReports")}
          description={t("reportList.noReportsDescription")}
          icon={FileText}
          className="border-none shadow-none"
        />
      ) : (
        <div className="rounded-md border bg-card">
          <Table>
            <caption className="sr-only">{t("reportList.caption")}</caption>
            <TableHeader>
              <TableRow>
                <TableHead>{t("reportList.typeColumn")}</TableHead>
                <TableHead>{t("reportList.studentTargetColumn")}</TableHead>
                <TableHead>{t("reportList.periodColumn")}</TableHead>
                <TableHead className="text-right">{t("reportList.scoreColumn")}</TableHead>
                <TableHead>{t("reportList.confidenceColumn")}</TableHead>
                <TableHead>{t("reportList.statusColumn")}</TableHead>
                <TableHead>{t("reportList.generatedByColumn")}</TableHead>
                <TableHead>{t("reportList.dateColumn")}</TableHead>
                <TableHead className="w-40">{t("reportList.actionsColumn")}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {reports.map((r) => (
                <TableRow key={r.id}>
                  <TableCell>
                    <Badge variant="outline">{typeLabel(r.reportType)}</Badge>
                  </TableCell>
                  <TableCell className="font-medium">{studentTargetDisplay(r)}</TableCell>
                  <TableCell>{r.period ?? "-"}</TableCell>
                  <TableCell className="text-right font-mono">
                    {r.overallScore !== null ? `${r.overallScore.toFixed(1)}%` : "-"}
                  </TableCell>
                  <TableCell>
                    {(() => {
                      const level = getConfidenceLevel(r)
                      return (
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Badge
                              variant={confidenceBadgeVariant[level]}
                              aria-label={t("reportList.confidenceAriaLabel", { level: confidenceLabel(level) })}
                            >
                              {confidenceLabel(level)}
                            </Badge>
                          </TooltipTrigger>
                          <TooltipContent>{confidenceHint(level)}</TooltipContent>
                        </Tooltip>
                      )
                    })()}
                  </TableCell>
                  <TableCell>
                    <Badge variant={statusColors[r.status] ?? "secondary"}>{statusLabel(r.status)}</Badge>
                  </TableCell>
                  <TableCell className="text-muted-foreground">{r.generatedByName ?? "-"}</TableCell>
                  <TableCell className="text-muted-foreground">{formatDate(r.createdAt)}</TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      {/* v3-P2-4: 导出按钮（所有角色可见，受 exportDiagnosticReportAction 权限校验保护） */}
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-8 w-8"
                        onClick={() => handleExport(r.id)}
                        disabled={isBusy}
                        title={t("report.export")}
                        aria-label={t("reportList.exportAriaLabel", { studentName: r.studentName ?? "" })}
                      >
                        <Download className="h-4 w-4" />
                      </Button>
                      {canManage && r.status === "draft" ? (
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 text-green-600"
                          onClick={() => setPublishId(r.id)}
                          disabled={isBusy}
                          title={t("report.publish")}
                          aria-label={t("reportList.publishAriaLabel", { studentName: r.studentName ?? "" })}
                        >
                          <Send className="h-4 w-4" />
                        </Button>
                      ) : null}
                      {canManage ? (
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-8 w-8 text-destructive"
                          onClick={() => setDeleteId(r.id)}
                          disabled={isBusy}
                          title={t("report.delete")}
                          aria-label={t("reportList.deleteAriaLabel", { studentName: r.studentName ?? "" })}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      ) : null}
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      {/* 发布确认 */}
      <Dialog open={publishId !== null} onOpenChange={(open) => !open && setPublishId(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t("report.publishTitle")}</DialogTitle>
            <DialogDescription>
              {t("reportList.publishConfirmation")}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setPublishId(null)} disabled={isBusy}>
              {t("report.cancel")}
            </Button>
            <Button onClick={handlePublish} disabled={isBusy}>
              {isBusy ? t("report.publishing") : t("report.publish")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认 */}
      <Dialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t("report.deleteTitle")}</DialogTitle>
            <DialogDescription>
              {t("report.deleteConfirmation")}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteId(null)} disabled={isBusy}>
              {t("report.cancel")}
            </Button>
            <Button variant="destructive" onClick={handleDelete} disabled={isBusy}>
              {isBusy ? t("report.deleting") : t("report.delete")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
