"use client"

import type { JSX } from "react"
import { useState } from "react"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import { useTranslations } from "next-intl"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Textarea } from "@/shared/components/ui/textarea"
import { Checkbox } from "@/shared/components/ui/checkbox"
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 { StatusBadge } from "@/shared/components/ui/status-badge"
import { formatDate } from "@/shared/lib/utils"
import { safeActionCall } from "@/shared/lib/action-utils"
import { Trash2, Pencil } from "lucide-react"

import { deleteGradeRecordAction, updateGradeRecordAction, bulkDeleteGradeRecordsAction } from "../actions"
import type { GradeRecordListItem, GradeRecordType, GradeRecordSemester } from "../types"
import { GRADE_TYPE_VARIANT } from "../types"
import { isGradeType, isSemester } from "../lib/type-guards"
import { ScoreCell } from "./score-cell"

type EditableFields = {
  id: string
  title: string
  score: string
  fullScore: string
  type: GradeRecordType
  semester: GradeRecordSemester
  remark: string
}

export function GradeRecordList({ records }: { records: GradeRecordListItem[] }): JSX.Element {
  const t = useTranslations("grades")
  const router = useRouter()
  const [deleteId, setDeleteId] = useState<string | null>(null)
  const [isDeleting, setIsDeleting] = useState(false)
  const [editTarget, setEditTarget] = useState<EditableFields | null>(null)
  const [isSaving, setIsSaving] = useState(false)
  // v3-P3-2: 批量选择与删除
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
  const [isBulkDeleteDialogOpen, setIsBulkDeleteDialogOpen] = useState(false)
  const [isBulkDeleting, setIsBulkDeleting] = useState(false)

  const handleDelete = async () => {
    if (!deleteId) return
    setIsDeleting(true)
    const result = await safeActionCall(
      () => deleteGradeRecordAction(deleteId),
      {
        onError: () => toast.error(t("error.deleteFailed")),
        onFinally: () => setIsDeleting(false),
      }
    )
    if (result?.success) {
      toast.success(result.message)
      setDeleteId(null)
      router.refresh()
    } else if (result) {
      toast.error(result.message || t("error.deleteFailed"))
    }
  }

  // v3-P3-2: 切换单行选择
  const toggleRowSelection = (id: string): void => {
    setSelectedIds((prev) => {
      const next = new Set(prev)
      if (next.has(id)) {
        next.delete(id)
      } else {
        next.add(id)
      }
      return next
    })
  }

  // v3-P3-2: 全选/取消全选
  const toggleSelectAll = (): void => {
    setSelectedIds((prev) => {
      if (prev.size === records.length) {
        return new Set()
      }
      return new Set(records.map((r) => r.id))
    })
  }

  // v3-P3-2: 清空选择
  const clearSelection = (): void => {
    setSelectedIds(new Set())
  }

  // v3-P3-2: 批量删除
  const handleBulkDelete = async (): Promise<void> => {
    if (selectedIds.size === 0) return
    setIsBulkDeleting(true)
    const ids = Array.from(selectedIds)
    const result = await safeActionCall(
      () => bulkDeleteGradeRecordsAction(ids),
      {
        onError: () => toast.error(t("list.bulkDeleteFailed")),
        onFinally: () => setIsBulkDeleting(false),
      }
    )
    if (result?.success) {
      toast.success(t("list.bulkDeleteSuccess", { count: result.data ?? 0 }))
      clearSelection()
      setIsBulkDeleteDialogOpen(false)
      router.refresh()
    } else if (result) {
      toast.error(result.message || t("list.bulkDeleteFailed"))
    }
  }

  const startEdit = (r: GradeRecordListItem): void => {
    setEditTarget({
      id: r.id,
      title: r.title,
      score: String(r.score),
      fullScore: String(r.fullScore),
      type: r.type,
      semester: r.semester,
      remark: r.remark ?? "",
    })
  }

  const handleEditSave = async (): Promise<void> => {
    if (!editTarget) return
    setIsSaving(true)
    const formData = new FormData()
    formData.set("title", editTarget.title)
    formData.set("score", editTarget.score)
    formData.set("fullScore", editTarget.fullScore)
    formData.set("type", editTarget.type)
    formData.set("semester", editTarget.semester)
    formData.set("remark", editTarget.remark)

    const result = await safeActionCall(
      () => updateGradeRecordAction(editTarget.id, null, formData),
      {
        onError: () => toast.error(t("edit.failed")),
        onFinally: () => setIsSaving(false),
      }
    )
    if (result?.success) {
      toast.success(t("edit.success"))
      setEditTarget(null)
      router.refresh()
    } else if (result) {
      toast.error(result.message || t("edit.failed"))
    }
  }

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

  return (
    <>
      <div className="rounded-md border bg-card">
        {/* v3-P3-2: 批量操作工具栏 */}
        {selectedIds.size > 0 && (
          <div className="flex items-center justify-between gap-2 border-b bg-muted/40 px-4 py-2">
            <span className="text-sm text-muted-foreground">
              {t("list.bulkDeleteSelected", { count: selectedIds.size })}
            </span>
            <div className="flex items-center gap-2">
              <Button
                variant="ghost"
                size="sm"
                onClick={clearSelection}
                disabled={isBulkDeleting}
              >
                {t("list.clearSelection")}
              </Button>
              <Button
                variant="destructive"
                size="sm"
                onClick={() => setIsBulkDeleteDialogOpen(true)}
                disabled={isBulkDeleting}
              >
                <Trash2 className="mr-1.5 h-3.5 w-3.5" aria-hidden="true" />
                {t("list.bulkDelete")}
              </Button>
            </div>
          </div>
        )}
        {/* v4-P1-10: 桌面端表格（md 及以上显示） */}
        <div className="hidden overflow-x-auto md:block">
          <Table>
            <caption className="sr-only">{t("list.caption")}</caption>
            <TableHeader>
              <TableRow>
                <TableHead className="w-12">
                  <Checkbox
                    checked={records.length > 0 && selectedIds.size === records.length}
                    onCheckedChange={toggleSelectAll}
                    aria-label={t("list.selectAll")}
                  />
                </TableHead>
                <TableHead>{t("list.columns.student")}</TableHead>
                <TableHead>{t("list.columns.class")}</TableHead>
                <TableHead>{t("list.columns.subject")}</TableHead>
                <TableHead>{t("list.columns.title")}</TableHead>
                <TableHead className="text-right">{t("list.columns.score")}</TableHead>
                <TableHead>{t("list.columns.type")}</TableHead>
                <TableHead>{t("list.columns.semester")}</TableHead>
                <TableHead>{t("list.columns.recordedBy")}</TableHead>
                <TableHead>{t("list.columns.date")}</TableHead>
                <TableHead className="w-24">{t("list.columns.actions")}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {records.map((r) => (
                <TableRow key={r.id}>
                  <TableCell>
                    <Checkbox
                      checked={selectedIds.has(r.id)}
                      onCheckedChange={() => toggleRowSelection(r.id)}
                      aria-label={t("list.selectRow", { name: r.studentName })}
                    />
                  </TableCell>
                  <TableCell className="font-medium">{r.studentName}</TableCell>
                  <TableCell>{r.className}</TableCell>
                  <TableCell>{r.subjectName}</TableCell>
                  <TableCell>{r.title}</TableCell>
                  <TableCell className="text-right">
                    {/* v4-P1-7: 成绩颜色编码 */}
                    <ScoreCell score={r.score} fullScore={r.fullScore} />
                  </TableCell>
                  <TableCell>
                    <StatusBadge status={r.type} variantMap={GRADE_TYPE_VARIANT} />
                  </TableCell>
                  <TableCell>{t(`semester.s${r.semester}`)}</TableCell>
                  <TableCell className="text-muted-foreground">{r.recorderName}</TableCell>
                  <TableCell className="text-muted-foreground">{formatDate(r.createdAt)}</TableCell>
                  <TableCell>
                    <div className="flex items-center gap-1">
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-8 w-8"
                        onClick={() => startEdit(r)}
                        aria-label={t("list.editAriaLabel", { studentName: r.studentName, subjectName: r.subjectName })}
                      >
                        <Pencil className="h-4 w-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-8 w-8 text-destructive"
                        onClick={() => setDeleteId(r.id)}
                        aria-label={t("list.deleteAriaLabel", { studentName: r.studentName, subjectName: r.subjectName })}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>

        {/* P3-8: 移动端卡片堆叠视图（md 以下显示） */}
        <div
          className="block space-y-3 p-4 md:hidden"
          role="list"
          aria-label={t("list.caption")}
        >
          {records.map((r) => (
            <div
              key={r.id}
              className="rounded-md border border-border/60 bg-background p-3 shadow-sm"
              role="listitem"
            >
              <div className="flex items-start justify-between gap-3">
                <div className="flex items-center gap-2">
                  <Checkbox
                    checked={selectedIds.has(r.id)}
                    onCheckedChange={() => toggleRowSelection(r.id)}
                    aria-label={t("list.selectRow", { name: r.studentName })}
                  />
                  <div>
                    <div className="font-medium">{r.studentName}</div>
                    <div className="text-xs text-muted-foreground">
                      {r.className} · {r.subjectName}
                    </div>
                  </div>
                </div>
                <div className="text-right">
                  <ScoreCell score={r.score} fullScore={r.fullScore} />
                  <div className="mt-1 flex items-center justify-end gap-1.5">
                    <StatusBadge status={r.type} variantMap={GRADE_TYPE_VARIANT} />
                    <span className="text-xs text-muted-foreground">
                      {t(`semester.s${r.semester}`)}
                    </span>
                  </div>
                </div>
              </div>
              <div className="mt-2 border-t border-border/40 pt-2">
                <div className="text-sm">{r.title}</div>
                <div className="mt-1 text-xs text-muted-foreground">
                  {r.recorderName} · {formatDate(r.createdAt)}
                </div>
              </div>
              <div className="mt-2 flex items-center justify-end gap-1">
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-8"
                  onClick={() => startEdit(r)}
                  aria-label={t("list.editAriaLabel", { studentName: r.studentName, subjectName: r.subjectName })}
                >
                  <Pencil className="mr-1 h-3.5 w-3.5" aria-hidden="true" />
                  {t("edit.title")}
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-8 text-destructive"
                  onClick={() => setDeleteId(r.id)}
                  aria-label={t("list.deleteAriaLabel", { studentName: r.studentName, subjectName: r.subjectName })}
                >
                  <Trash2 className="mr-1 h-3.5 w-3.5" aria-hidden="true" />
                  {t("delete.title")}
                </Button>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 编辑对话框 */}
      <Dialog open={editTarget !== null} onOpenChange={(open) => !open && setEditTarget(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t("edit.title")}</DialogTitle>
            <DialogDescription>
              {editTarget?.title}
            </DialogDescription>
          </DialogHeader>
          {editTarget && (
            <div className="grid grid-cols-1 gap-4 py-2 md:grid-cols-2">
              <div className="grid gap-2 md:col-span-2">
                <Label htmlFor="edit-title">{t("edit.titleLabel")}</Label>
                <Input
                  id="edit-title"
                  value={editTarget.title}
                  onChange={(e) => setEditTarget({ ...editTarget, title: e.target.value })}
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="edit-score">{t("edit.score")}</Label>
                <Input
                  id="edit-score"
                  type="number"
                  step="0.01"
                  min="0"
                  value={editTarget.score}
                  onChange={(e) => setEditTarget({ ...editTarget, score: e.target.value })}
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="edit-fullScore">{t("edit.fullScore")}</Label>
                <Input
                  id="edit-fullScore"
                  type="number"
                  step="0.01"
                  min="1"
                  value={editTarget.fullScore}
                  onChange={(e) => setEditTarget({ ...editTarget, fullScore: e.target.value })}
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="edit-type">{t("filters.type")}</Label>
                <Select
                  value={editTarget.type}
                  onValueChange={(v) => { if (isGradeType(v)) setEditTarget({ ...editTarget, type: v }) }}
                >
                  <SelectTrigger id="edit-type">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="exam">{t("type.exam")}</SelectItem>
                    <SelectItem value="quiz">{t("type.quiz")}</SelectItem>
                    <SelectItem value="homework">{t("type.homework")}</SelectItem>
                    <SelectItem value="other">{t("type.other")}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="grid gap-2">
                <Label htmlFor="edit-semester">{t("filters.semester")}</Label>
                <Select
                  value={editTarget.semester}
                  onValueChange={(v) => { if (isSemester(v)) setEditTarget({ ...editTarget, semester: v }) }}
                >
                  <SelectTrigger id="edit-semester">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="1">{t("semester.s1")}</SelectItem>
                    <SelectItem value="2">{t("semester.s2")}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="grid gap-2 md:col-span-2">
                <Label htmlFor="edit-remark">{t("edit.remark")}</Label>
                <Textarea
                  id="edit-remark"
                  placeholder={t("edit.remarkPlaceholder")}
                  value={editTarget.remark}
                  onChange={(e) => setEditTarget({ ...editTarget, remark: e.target.value })}
                />
              </div>
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setEditTarget(null)} disabled={isSaving}>
              {t("edit.cancel")}
            </Button>
            <Button onClick={handleEditSave} disabled={isSaving}>
              {isSaving ? t("edit.saving") : t("edit.confirm")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={deleteId !== null} onOpenChange={(open) => !open && setDeleteId(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t("delete.title")}</DialogTitle>
            <DialogDescription>
              {t("delete.confirmation")}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDeleteId(null)} disabled={isDeleting}>
              {t("delete.cancel")}
            </Button>
            <Button variant="destructive" onClick={handleDelete} disabled={isDeleting}>
              {isDeleting ? t("delete.deleting") : t("delete.confirm")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* v3-P3-2: 批量删除确认对话框 */}
      <Dialog open={isBulkDeleteDialogOpen} onOpenChange={(open) => !open && setIsBulkDeleteDialogOpen(open)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>{t("list.bulkDelete")}</DialogTitle>
            <DialogDescription>
              {t("list.bulkDeleteConfirmation", { count: selectedIds.size })}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsBulkDeleteDialogOpen(false)}
              disabled={isBulkDeleting}
            >
              {t("delete.cancel")}
            </Button>
            <Button variant="destructive" onClick={handleBulkDelete} disabled={isBulkDeleting}>
              {isBulkDeleting ? t("delete.deleting") : t("delete.confirm")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}
