"use client"

import { useState } from "react"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import { Button } from "@/shared/components/ui/button"
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 { StatusBadge } from "@/shared/components/ui/status-badge"
import { formatDate } from "@/shared/lib/utils"
import { Trash2 } from "lucide-react"

import { deleteGradeRecordAction } from "../actions"
import type { GradeRecordListItem } from "../types"
import { GRADE_TYPE_VARIANT } from "../types"

export function GradeRecordList({ records }: { records: GradeRecordListItem[] }) {
  const router = useRouter()
  const [deleteId, setDeleteId] = useState<string | null>(null)
  const [isDeleting, setIsDeleting] = useState(false)

  const handleDelete = async () => {
    if (!deleteId) return
    setIsDeleting(true)
    const result = await deleteGradeRecordAction(deleteId)
    setIsDeleting(false)
    if (result.success) {
      toast.success(result.message)
      setDeleteId(null)
      router.refresh()
    } else {
      toast.error(result.message || "Failed to delete")
    }
  }

  if (records.length === 0) {
    return (
      <div className="rounded-md border bg-card p-8 text-center text-sm text-muted-foreground">
        No grade records found.
      </div>
    )
  }

  return (
    <>
      <div className="rounded-md border bg-card">
        <Table>
          <caption className="sr-only">成绩记录列表</caption>
          <TableHeader>
            <TableRow>
              <TableHead>Student</TableHead>
              <TableHead>Class</TableHead>
              <TableHead>Subject</TableHead>
              <TableHead>Title</TableHead>
              <TableHead className="text-right">Score</TableHead>
              <TableHead>Type</TableHead>
              <TableHead>Semester</TableHead>
              <TableHead>Recorded By</TableHead>
              <TableHead>Date</TableHead>
              <TableHead className="w-12"></TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {records.map((r) => (
              <TableRow key={r.id}>
                <TableCell className="font-medium">{r.studentName}</TableCell>
                <TableCell>{r.className}</TableCell>
                <TableCell>{r.subjectName}</TableCell>
                <TableCell>{r.title}</TableCell>
                <TableCell className="text-right font-mono">
                  {r.score} / {r.fullScore}
                </TableCell>
                <TableCell>
                  <StatusBadge status={r.type} variantMap={GRADE_TYPE_VARIANT} />
                </TableCell>
                <TableCell>S{r.semester}</TableCell>
                <TableCell className="text-muted-foreground">{r.recorderName}</TableCell>
                <TableCell className="text-muted-foreground">{formatDate(r.createdAt)}</TableCell>
                <TableCell>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8 text-destructive"
                    onClick={() => setDeleteId(r.id)}
                    aria-label={`删除 ${r.studentName} 的 ${r.subjectName} 成绩记录`}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      <Dialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete Grade Record</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete this grade record? This action cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteId(null)} disabled={isDeleting}>
              Cancel
            </Button>
            <Button variant="destructive" onClick={handleDelete} disabled={isDeleting}>
              {isDeleting ? "Deleting..." : "Delete"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}
