"use client"

import { useMemo, useState } from "react"
import type { ReactNode } from "react"
import { MoreHorizontal, Pencil, Trash2 } from "lucide-react"
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 { useGradeData } from "../hooks/use-grade-data"
import { GradeDeleteDialog } from "./grade-delete-dialog"
import { GradeFormDialog } from "./grade-form-dialog"
import { GradeListToolbar } from "./grade-list-toolbar"
import { GradeOverviewCards } from "./grade-overview-cards"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/shared/components/ui/table"
import { EmptyState } from "@/shared/components/ui/empty-state"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"
import { formatDate } from "@/shared/lib/utils"

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

  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"))

  // 表单对话框会话 key：每次打开对话框时递增，强制 GradeFormDialog 重新挂载以重置表单状态
  const [formSession, setFormSession] = useState(0)

  const openCreate = (): void => {
    setFormSession((s) => s + 1)
    setCreateOpen(true)
  }

  const openEdit = (item: GradeListItem): void => {
    setFormSession((s) => s + 1)
    setEditItem(item)
  }

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

  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 handleResetFilters = (): void => {
    setQ(null)
    setSchool(null)
    setHead(null)
    setSort(null)
  }

  const handleFormOpenChange = (open: boolean): void => {
    if (!open) {
      setCreateOpen(false)
      setEditItem(null)
    }
  }

  const handleDeleteOpenChange = (open: boolean): void => {
    if (!open) {
      setDeleteItem(null)
    }
  }

  const handleSuccess = (): void => {
    router.refresh()
  }

  const formatStaffDetail = (u: StaffOption | null): ReactNode => {
    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>
    )
  }

  return (
    <>
      {/* 年级概览卡片视图：让管理员一目了然看到各年级规模 */}
      {filteredGrades.length > 0 && (
        <GradeOverviewCards
          grades={filteredGrades}
          statsMap={statsMap}
          isWorking={isWorking}
          onEdit={openEdit}
          onDelete={setDeleteItem}
        />
      )}

      <GradeListToolbar
        q={q}
        setQ={setQ}
        school={school}
        setSchool={setSchool}
        head={head}
        setHead={setHead}
        sort={sort}
        setSort={setSort}
        hasFilters={hasFilters}
        onReset={handleResetFilters}
        schools={schools}
        onCreate={openCreate}
        isWorking={isWorking}
      />

      <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>

      <GradeFormDialog
        key={formSession}
        open={createOpen || Boolean(editItem)}
        onOpenChange={handleFormOpenChange}
        editItem={editItem}
        schools={schools}
        staff={staff}
        grades={grades}
        onSuccess={handleSuccess}
      />

      <GradeDeleteDialog
        deleteItem={deleteItem}
        onOpenChange={handleDeleteOpenChange}
        onSuccess={handleSuccess}
      />
    </>
  )
}
