"use client"

import { useCallback, useEffect, useMemo, useState } from "react"
import { BarChart3, MoreHorizontal, Pencil, Plus, Trash2, Users, GraduationCap, UserCog } from "lucide-react"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import { parseAsString, useQueryState } from "nuqs"
import { useTranslations } from "next-intl"

import type { GradeListItem, SchoolListItem, StaffOption } from "../types"
import type { GradeOverviewStats } from "../data-access"
import { createGradeAction, deleteGradeAction, updateGradeAction } from "../actions"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/shared/components/ui/dialog"
import { Input } from "@/shared/components/ui/input"
import { Label } from "@/shared/components/ui/label"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { Badge } from "@/shared/components/ui/badge"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/components/ui/alert-dialog"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/shared/components/ui/select"
import { formatDate } from "@/shared/lib/utils"

type FormState = {
  schoolId: string
  name: string
  order: string
  gradeHeadId: string
  teachingHeadId: string
}

const toFormState = (item: GradeListItem | null, fallbackSchoolId: string): FormState => ({
  schoolId: item?.school.id ?? fallbackSchoolId,
  name: item?.name ?? "",
  order: String(item?.order ?? 0),
  gradeHeadId: item?.gradeHead?.id ?? "",
  teachingHeadId: item?.teachingHead?.id ?? "",
})

type FormErrors = Partial<Record<keyof FormState, string>>

const normalizeName = (v: string) => v.trim().replace(/\s+/g, " ")

const NONE_SELECT_VALUE = "__none__"

const parseOrder = (raw: string) => {
  const v = raw.trim()
  if (!v) return 0
  const n = Number(v)
  if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0) return null
  return n
}

export function GradesClient({
  grades,
  schools,
  staff,
  gradeStats,
}: {
  grades: GradeListItem[]
  schools: SchoolListItem[]
  staff: StaffOption[]
  gradeStats: GradeOverviewStats[]
}) {
  const t = useTranslations("school")
  const router = useRouter()
  const [isWorking, setIsWorking] = useState(false)
  const [createOpen, setCreateOpen] = useState(false)
  const [editItem, setEditItem] = useState<GradeListItem | null>(null)
  const [deleteItem, setDeleteItem] = useState<GradeListItem | null>(null)

  const [q, setQ] = useQueryState("q", parseAsString.withDefault(""))
  const [school, setSchool] = useQueryState("school", parseAsString.withDefault("all"))
  const [head, setHead] = useQueryState("head", parseAsString.withDefault("all"))
  const [sort, setSort] = useQueryState("sort", parseAsString.withDefault("default"))

  const defaultSchoolId = useMemo(() => schools[0]?.id ?? "", [schools])
  const [createState, setCreateState] = useState<FormState>(() => toFormState(null, defaultSchoolId))
  const [editState, setEditState] = useState<FormState>(() => toFormState(null, defaultSchoolId))

  // 年级概览统计映射，用于卡片视图
  const statsMap = useMemo(() => {
    const m = new Map<string, GradeOverviewStats>()
    for (const s of gradeStats) m.set(s.gradeId, s)
    return m
  }, [gradeStats])

  useEffect(() => {
    if (!createOpen) return
    if (createState.schoolId.trim().length > 0) return
    if (!defaultSchoolId) return
    setCreateState((p) => ({ ...p, schoolId: defaultSchoolId }))
  }, [createOpen, createState.schoolId, defaultSchoolId])

  useEffect(() => {
    if (!editItem) return
    if (editState.schoolId.trim().length > 0) return
    if (!defaultSchoolId) return
    setEditState((p) => ({ ...p, schoolId: defaultSchoolId }))
  }, [editItem, editState.schoolId, defaultSchoolId])

  const staffOptions = useMemo(() => {
    return [...staff].sort((a, b) => {
      const byName = a.name.localeCompare(b.name)
      if (byName !== 0) return byName
      return a.email.localeCompare(b.email)
    })
  }, [staff])

  const validateForm = useCallback(
    (state: FormState, params: { grades: GradeListItem[]; excludeGradeId?: string }): {
      ok: boolean
      errors: FormErrors
    } => {
      const errors: FormErrors = {}

      const schoolId = state.schoolId.trim()
      if (!schoolId) errors.schoolId = t("grades.validation.selectSchool")

      const name = normalizeName(state.name)
      if (!name) errors.name = t("grades.validation.enterName")
      if (name.length > 100) errors.name = t("grades.validation.nameTooLong")

      const order = parseOrder(state.order)
      if (order === null) errors.order = t("grades.validation.orderInvalid")

      if (schoolId && name) {
        const dup = params.grades.find((g) => {
          if (params.excludeGradeId && g.id === params.excludeGradeId) return false
          return g.school.id === schoolId && normalizeName(g.name).toLowerCase() === name.toLowerCase()
        })
        if (dup) errors.name = t("grades.validation.duplicateName")
      }

      return { ok: Object.keys(errors).length === 0, errors }
    },
    [t]
  )

  const formatStaffDetail = (u: StaffOption | null) => {
    if (!u) return <Badge variant="outline">{t("grades.notSet")}</Badge>
    return (
      <div className="min-w-0">
        <div className="truncate">{u.name}</div>
        <div className="truncate text-xs text-muted-foreground">{u.email}</div>
      </div>
    )
  }

  const filteredGrades = useMemo(() => {
    const needle = q.trim().toLowerCase()
    const bySchool = school === "all" ? "" : school

    return grades
      .filter((g) => {
        if (bySchool && g.school.id !== bySchool) return false
        if (head === "missing") {
          if (g.gradeHead || g.teachingHead) return false
        }
        if (head === "missing_grade_head") {
          if (g.gradeHead) return false
        }
        if (head === "missing_teaching_head") {
          if (g.teachingHead) return false
        }

        if (!needle) return true
        const hay = [
          g.name,
          g.school.name,
          g.gradeHead?.name ?? "",
          g.gradeHead?.email ?? "",
          g.teachingHead?.name ?? "",
          g.teachingHead?.email ?? "",
        ]
          .join(" ")
          .toLowerCase()
        return hay.includes(needle)
      })
      .sort((a, b) => {
        if (sort === "updated_desc") return b.updatedAt.localeCompare(a.updatedAt)
        if (sort === "updated_asc") return a.updatedAt.localeCompare(b.updatedAt)
        if (sort === "name_asc") return a.name.localeCompare(b.name)
        if (sort === "name_desc") return b.name.localeCompare(a.name)
        if (sort === "order_asc") return a.order - b.order
        if (sort === "order_desc") return b.order - a.order
        return 0
      })
  }, [grades, head, q, school, sort])

  const hasFilters = q.length > 0 || school !== "all" || head !== "all" || sort !== "default"

  const openEdit = (item: GradeListItem) => {
    setEditItem(item)
    setEditState(toFormState(item, defaultSchoolId))
  }

  const openCreate = () => {
    setCreateState(toFormState(null, defaultSchoolId))
    setCreateOpen(true)
  }

  const createValidation = useMemo(
    () => validateForm(createState, { grades }),
    [createState, grades, validateForm]
  )
  const editValidation = useMemo(
    () => validateForm(editState, { grades, excludeGradeId: editItem?.id }),
    [editItem?.id, editState, grades, validateForm]
  )

  const isEditDirty = useMemo(() => {
    if (!editItem) return false
    const next = {
      schoolId: editState.schoolId.trim(),
      name: normalizeName(editState.name),
      order: parseOrder(editState.order),
      gradeHeadId: editState.gradeHeadId || "",
      teachingHeadId: editState.teachingHeadId || "",
    }
    const prev = {
      schoolId: editItem.school.id,
      name: normalizeName(editItem.name),
      order: editItem.order,
      gradeHeadId: editItem.gradeHead?.id ?? "",
      teachingHeadId: editItem.teachingHead?.id ?? "",
    }
    return (
      next.schoolId !== prev.schoolId ||
      next.name !== prev.name ||
      (typeof next.order === "number" ? next.order : null) !== prev.order ||
      next.gradeHeadId !== prev.gradeHeadId ||
      next.teachingHeadId !== prev.teachingHeadId
    )
  }, [editItem, editState])

  const handleCreate = async () => {
    const validation = validateForm(createState, { grades })
    if (!validation.ok) {
      toast.error(Object.values(validation.errors)[0] || t("grades.validation.fixForm"))
      return
    }

    setIsWorking(true)
    try {
      const fd = new FormData()
      fd.set("schoolId", createState.schoolId)
      fd.set("name", normalizeName(createState.name))
      fd.set("order", createState.order)
      fd.set("gradeHeadId", createState.gradeHeadId)
      fd.set("teachingHeadId", createState.teachingHeadId)

      const res = await createGradeAction(undefined, fd)
      if (res.success) {
        toast.success(res.message)
        setCreateOpen(false)
        router.refresh()
      } else {
        toast.error(res.message || t("grades.failedCreate"))
      }
    } catch {
      toast.error(t("grades.failedCreate"))
    } finally {
      setIsWorking(false)
    }
  }

  const handleUpdate = async () => {
    if (!editItem) return
    const validation = validateForm(editState, { grades, excludeGradeId: editItem.id })
    if (!validation.ok) {
      toast.error(Object.values(validation.errors)[0] || t("grades.validation.fixForm"))
      return
    }
    if (!isEditDirty) {
      toast.message(t("grades.validation.noChanges"))
      return
    }

    setIsWorking(true)
    try {
      const fd = new FormData()
      fd.set("schoolId", editState.schoolId)
      fd.set("name", normalizeName(editState.name))
      fd.set("order", editState.order)
      fd.set("gradeHeadId", editState.gradeHeadId)
      fd.set("teachingHeadId", editState.teachingHeadId)

      const res = await updateGradeAction(editItem.id, undefined, fd)
      if (res.success) {
        toast.success(res.message)
        setEditItem(null)
        router.refresh()
      } else {
        toast.error(res.message || t("grades.failedUpdate"))
      }
    } catch {
      toast.error(t("grades.failedUpdate"))
    } finally {
      setIsWorking(false)
    }
  }

  const handleDelete = async () => {
    if (!deleteItem) return
    setIsWorking(true)
    try {
      const res = await deleteGradeAction(deleteItem.id)
      if (res.success) {
        toast.success(res.message)
        setDeleteItem(null)
        router.refresh()
      } else {
        toast.error(res.message || t("grades.failedDelete"))
      }
    } catch {
      toast.error(t("grades.failedDelete"))
    } finally {
      setIsWorking(false)
    }
  }

  return (
    <>
      {/* 年级概览卡片视图：让管理员一目了然看到各年级规模 */}
      {filteredGrades.length > 0 && (
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {filteredGrades.slice(0, 8).map((g) => {
            const stats = statsMap.get(g.id)
            return (
              <Card key={g.id} className="shadow-none">
                <CardContent className="space-y-3 p-4">
                  <div className="flex items-start justify-between">
                    <div className="min-w-0 flex-1">
                      <div className="truncate text-sm font-semibold">{g.name}</div>
                      <div className="truncate text-xs text-muted-foreground">{g.school.name}</div>
                    </div>
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button variant="ghost" size="icon" className="h-7 w-7 shrink-0" disabled={isWorking}>
                          <MoreHorizontal className="h-3.5 w-3.5" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end">
                        <DropdownMenuItem
                          onClick={() =>
                            router.push(`/admin/school/grades/insights?gradeId=${encodeURIComponent(g.id)}`)
                          }
                        >
                          <BarChart3 className="mr-2 h-3.5 w-3.5" />
                          {t("grades.gradeOverview.viewInsights")}
                        </DropdownMenuItem>
                        <DropdownMenuSeparator />
                        <DropdownMenuItem onClick={() => openEdit(g)}>
                          <Pencil className="mr-2 h-3.5 w-3.5" />
                          {t("grades.actions.edit")}
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          className="text-destructive focus:text-destructive"
                          onClick={() => setDeleteItem(g)}
                        >
                          <Trash2 className="mr-2 h-3.5 w-3.5" />
                          {t("grades.actions.delete")}
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </div>

                  {/* 统计指标 */}
                  <div className="grid grid-cols-3 gap-2 text-center">
                    <div className="rounded-md bg-muted/50 p-2">
                      <div className="flex items-center justify-center text-muted-foreground">
                        <GraduationCap className="h-3 w-3" />
                      </div>
                      <div className="mt-0.5 text-sm font-semibold tabular-nums">
                        {stats?.classCount ?? 0}
                      </div>
                      <div className="text-[10px] text-muted-foreground">
                        {t("grades.gradeOverview.classCount")}
                      </div>
                    </div>
                    <div className="rounded-md bg-muted/50 p-2">
                      <div className="flex items-center justify-center text-muted-foreground">
                        <Users className="h-3 w-3" />
                      </div>
                      <div className="mt-0.5 text-sm font-semibold tabular-nums">
                        {stats?.studentCount ?? 0}
                      </div>
                      <div className="text-[10px] text-muted-foreground">
                        {t("grades.gradeOverview.studentCount")}
                      </div>
                    </div>
                    <div className="rounded-md bg-muted/50 p-2">
                      <div className="flex items-center justify-center text-muted-foreground">
                        <UserCog className="h-3 w-3" />
                      </div>
                      <div className="mt-0.5 text-sm font-semibold tabular-nums">
                        {stats?.teacherCount ?? 0}
                      </div>
                      <div className="text-[10px] text-muted-foreground">
                        {t("grades.gradeOverview.teacherCount")}
                      </div>
                    </div>
                  </div>

                  {/* 年级主任/教学主任 */}
                  <div className="space-y-1 border-t pt-2 text-xs">
                    <div className="flex items-center justify-between">
                      <span className="text-muted-foreground">{t("grades.gradeOverview.gradeHead")}</span>
                      <span className="truncate font-medium">
                        {g.gradeHead?.name ?? t("grades.gradeOverview.notSet")}
                      </span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-muted-foreground">{t("grades.gradeOverview.teachingHead")}</span>
                      <span className="truncate font-medium">
                        {g.teachingHead?.name ?? t("grades.gradeOverview.notSet")}
                      </span>
                    </div>
                  </div>

                  {/* 快捷操作 */}
                  <Button
                    asChild
                    variant="outline"
                    size="sm"
                    className="w-full"
                  >
                    <a href={`/admin/school/grades/insights?gradeId=${encodeURIComponent(g.id)}`}>
                      <BarChart3 className="mr-1.5 h-3.5 w-3.5" />
                      {t("grades.gradeOverview.viewInsights")}
                    </a>
                  </Button>
                </CardContent>
              </Card>
            )
          })}
        </div>
      )}

      <div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
        <div className="flex flex-1 flex-col gap-2 md:flex-row md:items-center">
          <div className="flex-1 md:max-w-sm">
            <Input placeholder={t("grades.filters.search")} value={q} onChange={(e) => setQ(e.target.value || null)} />
          </div>

          <Select value={school} onValueChange={(v) => setSchool(v === "all" ? null : v)}>
            <SelectTrigger className="w-full md:w-[220px]">
              <SelectValue placeholder={t("grades.filters.school")} />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">{t("grades.filters.allSchools")}</SelectItem>
              {schools.map((s) => (
                <SelectItem key={s.id} value={s.id}>
                  {s.name}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          <Select value={head} onValueChange={(v) => setHead(v === "all" ? null : v)}>
            <SelectTrigger className="w-full md:w-[220px]">
              <SelectValue placeholder={t("grades.filters.head")} />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">{t("grades.filters.allHeads")}</SelectItem>
              <SelectItem value="missing">{t("grades.filters.missing")}</SelectItem>
              <SelectItem value="missing_grade_head">{t("grades.filters.missingGradeHead")}</SelectItem>
              <SelectItem value="missing_teaching_head">{t("grades.filters.missingTeachingHead")}</SelectItem>
            </SelectContent>
          </Select>

          <Select value={sort} onValueChange={(v) => setSort(v === "default" ? null : v)}>
            <SelectTrigger className="w-full md:w-[220px]">
              <SelectValue placeholder={t("grades.filters.sort")} />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="default">{t("grades.filters.defaultSort")}</SelectItem>
              <SelectItem value="updated_desc">{t("grades.filters.updatedDesc")}</SelectItem>
              <SelectItem value="updated_asc">{t("grades.filters.updatedAsc")}</SelectItem>
              <SelectItem value="name_asc">{t("grades.filters.nameAsc")}</SelectItem>
              <SelectItem value="name_desc">{t("grades.filters.nameDesc")}</SelectItem>
              <SelectItem value="order_asc">{t("grades.filters.orderAsc")}</SelectItem>
              <SelectItem value="order_desc">{t("grades.filters.orderDesc")}</SelectItem>
            </SelectContent>
          </Select>

          {hasFilters ? (
            <Button
              variant="outline"
              onClick={() => {
                setQ(null)
                setSchool(null)
                setHead(null)
                setSort(null)
              }}
            >
              {t("grades.filters.reset")}
            </Button>
          ) : null}
        </div>

        <Button onClick={openCreate} disabled={isWorking || schools.length === 0}>
          <Plus className="mr-2 h-4 w-4" />
          {t("grades.new")}
        </Button>
      </div>

      <Card className="shadow-none">
        <CardHeader className="flex flex-row items-center justify-between space-y-0">
          <CardTitle className="text-base">{t("grades.list.title")}</CardTitle>
          <div className="flex items-center gap-2">
            <Badge variant="secondary" className="tabular-nums">
              {filteredGrades.length}
            </Badge>
            {filteredGrades.length !== grades.length ? (
              <div className="text-xs text-muted-foreground tabular-nums">/ {grades.length}</div>
            ) : null}
          </div>
        </CardHeader>
        <CardContent>
          {schools.length === 0 ? (
            <EmptyState
              title={t("grades.list.noSchools")}
              description={t("grades.list.noSchoolsDescription")}
              className="h-auto border-none shadow-none"
            />
          ) : filteredGrades.length === 0 ? (
            <EmptyState
              title={grades.length === 0 ? t("grades.list.noGrades") : t("grades.list.noMatch")}
              description={
                grades.length === 0
                  ? t("grades.list.noGradesDescription")
                  : t("grades.list.noMatchDescription")
              }
              className="h-auto border-none shadow-none"
            />
          ) : (
            <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>{t("grades.column.school")}</TableHead>
                  <TableHead>{t("grades.column.grade")}</TableHead>
                  <TableHead>{t("grades.column.order")}</TableHead>
                  <TableHead>{t("grades.column.gradeHead")}</TableHead>
                  <TableHead>{t("grades.column.teachingHead")}</TableHead>
                  <TableHead>{t("grades.column.updated")}</TableHead>
                  <TableHead className="w-[60px]" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredGrades.map((g) => (
                  <TableRow key={g.id}>
                    <TableCell className="text-muted-foreground">{g.school.name}</TableCell>
                    <TableCell className="font-medium">{g.name}</TableCell>
                    <TableCell className="text-muted-foreground tabular-nums">{g.order}</TableCell>
                    <TableCell className="text-muted-foreground">{formatStaffDetail(g.gradeHead)}</TableCell>
                    <TableCell className="text-muted-foreground">{formatStaffDetail(g.teachingHead)}</TableCell>
                    <TableCell className="text-muted-foreground">{formatDate(g.updatedAt)}</TableCell>
                    <TableCell className="text-right">
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <Button variant="ghost" size="icon" className="h-8 w-8" disabled={isWorking}>
                            <MoreHorizontal className="h-4 w-4" />
                          </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                          <DropdownMenuItem
                            onClick={() =>
                              router.push(`/admin/school/grades/insights?gradeId=${encodeURIComponent(g.id)}`)
                            }
                          >
                            {t("grades.actions.insights")}
                          </DropdownMenuItem>
                          <DropdownMenuSeparator />
                          <DropdownMenuItem onClick={() => openEdit(g)}>
                            <Pencil className="mr-2 h-4 w-4" />
                            {t("grades.actions.edit")}
                          </DropdownMenuItem>
                          <DropdownMenuItem
                            className="text-destructive focus:text-destructive"
                            onClick={() => setDeleteItem(g)}
                          >
                            <Trash2 className="mr-2 h-4 w-4" />
                            {t("grades.actions.delete")}
                          </DropdownMenuItem>
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
            </div>
          )}
        </CardContent>
      </Card>

      <Dialog open={createOpen} onOpenChange={setCreateOpen}>
        <DialogContent className="sm:max-w-[560px]">
          <DialogHeader>
            <DialogTitle>{t("grades.form.createTitle")}</DialogTitle>
          </DialogHeader>
          <form
            className="space-y-4"
            onSubmit={(e) => {
              e.preventDefault()
              void handleCreate()
            }}
          >
            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">{t("grades.form.school")}</Label>
              <div className="col-span-3">
                <Select
                  value={createState.schoolId}
                  onValueChange={(v) => setCreateState((p) => ({ ...p, schoolId: v }))}
                >
                  <SelectTrigger>
                    <SelectValue placeholder={t("grades.form.school")} />
                  </SelectTrigger>
                  <SelectContent>
                    {schools.map((s) => (
                      <SelectItem key={s.id} value={s.id}>
                        {s.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              {createValidation.errors.schoolId ? (
                <div className="col-span-3 col-start-2 text-sm font-medium text-destructive">
                  {createValidation.errors.schoolId}
                </div>
              ) : null}
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="create-grade-name" className="text-right">
                {t("grades.form.name")}
              </Label>
              <Input
                id="create-grade-name"
                className="col-span-3"
                value={createState.name}
                onChange={(e) => setCreateState((p) => ({ ...p, name: e.target.value }))}
                placeholder={t("grades.form.name")}
                autoFocus
              />
              {createValidation.errors.name ? (
                <div className="col-span-3 col-start-2 text-sm font-medium text-destructive">
                  {createValidation.errors.name}
                </div>
              ) : null}
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label htmlFor="create-grade-order" className="text-right">
                {t("grades.form.order")}
              </Label>
              <Input
                id="create-grade-order"
                className="col-span-3"
                type="number"
                inputMode="numeric"
                min={0}
                step={1}
                value={createState.order}
                onChange={(e) => setCreateState((p) => ({ ...p, order: e.target.value }))}
              />
              {createValidation.errors.order ? (
                <div className="col-span-3 col-start-2 text-sm font-medium text-destructive">
                  {createValidation.errors.order}
                </div>
              ) : null}
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">{t("grades.form.gradeHead")}</Label>
              <div className="col-span-3">
                <Select
                  value={createState.gradeHeadId}
                  onValueChange={(v) =>
                    setCreateState((p) => ({ ...p, gradeHeadId: v === NONE_SELECT_VALUE ? "" : v }))
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder={t("grades.optional")} />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={NONE_SELECT_VALUE}>-</SelectItem>
                    {staffOptions.map((u) => (
                      <SelectItem key={u.id} value={u.id}>
                        {u.name} ({u.email})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            <div className="grid grid-cols-4 items-center gap-4">
              <Label className="text-right">{t("grades.form.teachingHead")}</Label>
              <div className="col-span-3">
                <Select
                  value={createState.teachingHeadId}
                  onValueChange={(v) =>
                    setCreateState((p) => ({ ...p, teachingHeadId: v === NONE_SELECT_VALUE ? "" : v }))
                  }
                >
                  <SelectTrigger>
                    <SelectValue placeholder={t("grades.optional")} />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value={NONE_SELECT_VALUE}>-</SelectItem>
                    {staffOptions.map((u) => (
                      <SelectItem key={u.id} value={u.id}>
                        {u.name} ({u.email})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>

            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setCreateOpen(false)} disabled={isWorking}>
                {t("grades.form.cancel")}
              </Button>
              <Button type="submit" disabled={isWorking}>
                {t("grades.form.create")}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      <Dialog
        open={Boolean(editItem)}
        onOpenChange={(open) => {
          if (!open) setEditItem(null)
        }}
      >
        <DialogContent className="sm:max-w-[560px]">
          <DialogHeader>
            <DialogTitle>{t("grades.form.editTitle")}</DialogTitle>
          </DialogHeader>
          {editItem ? (
            <form
              className="space-y-4"
              onSubmit={(e) => {
                e.preventDefault()
                void handleUpdate()
              }}
            >
              <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right">{t("grades.form.school")}</Label>
                <div className="col-span-3">
                  <Select
                    value={editState.schoolId}
                    onValueChange={(v) => setEditState((p) => ({ ...p, schoolId: v }))}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder={t("grades.form.school")} />
                    </SelectTrigger>
                    <SelectContent>
                      {schools.map((s) => (
                        <SelectItem key={s.id} value={s.id}>
                          {s.name}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                {editValidation.errors.schoolId ? (
                  <div className="col-span-3 col-start-2 text-sm font-medium text-destructive">
                    {editValidation.errors.schoolId}
                  </div>
                ) : null}
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-grade-name" className="text-right">
                  {t("grades.form.name")}
                </Label>
                <Input
                  id="edit-grade-name"
                  className="col-span-3"
                  value={editState.name}
                  onChange={(e) => setEditState((p) => ({ ...p, name: e.target.value }))}
                />
                {editValidation.errors.name ? (
                  <div className="col-span-3 col-start-2 text-sm font-medium text-destructive">
                    {editValidation.errors.name}
                  </div>
                ) : null}
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-grade-order" className="text-right">
                  {t("grades.form.order")}
                </Label>
                <Input
                  id="edit-grade-order"
                  className="col-span-3"
                  type="number"
                  inputMode="numeric"
                  min={0}
                  step={1}
                  value={editState.order}
                  onChange={(e) => setEditState((p) => ({ ...p, order: e.target.value }))}
                />
                {editValidation.errors.order ? (
                  <div className="col-span-3 col-start-2 text-sm font-medium text-destructive">
                    {editValidation.errors.order}
                  </div>
                ) : null}
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right">{t("grades.form.gradeHead")}</Label>
                <div className="col-span-3">
                  <Select
                    value={editState.gradeHeadId}
                    onValueChange={(v) =>
                      setEditState((p) => ({ ...p, gradeHeadId: v === NONE_SELECT_VALUE ? "" : v }))
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder={t("grades.optional")} />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value={NONE_SELECT_VALUE}>-</SelectItem>
                      {staffOptions.map((u) => (
                        <SelectItem key={u.id} value={u.id}>
                          {u.name} ({u.email})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="grid grid-cols-4 items-center gap-4">
                <Label className="text-right">{t("grades.form.teachingHead")}</Label>
                <div className="col-span-3">
                  <Select
                    value={editState.teachingHeadId}
                    onValueChange={(v) =>
                      setEditState((p) => ({ ...p, teachingHeadId: v === NONE_SELECT_VALUE ? "" : v }))
                    }
                  >
                    <SelectTrigger>
                      <SelectValue placeholder={t("grades.optional")} />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value={NONE_SELECT_VALUE}>-</SelectItem>
                      {staffOptions.map((u) => (
                        <SelectItem key={u.id} value={u.id}>
                          {u.name} ({u.email})
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <DialogFooter>
                <Button type="button" variant="outline" onClick={() => setEditItem(null)} disabled={isWorking}>
                  {t("grades.form.cancel")}
                </Button>
                <Button type="submit" disabled={isWorking}>
                  {t("grades.form.save")}
                </Button>
              </DialogFooter>
            </form>
          ) : null}
        </DialogContent>
      </Dialog>

      <AlertDialog
        open={Boolean(deleteItem)}
        onOpenChange={(open) => {
          if (!open) setDeleteItem(null)
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t("grades.delete.title")}</AlertDialogTitle>
            <AlertDialogDescription>
              {t("grades.delete.description", { name: deleteItem?.name || "" })}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isWorking}>{t("grades.delete.cancel")}</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} disabled={isWorking}>
              {t("grades.delete.confirm")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}
