"use client"

import { useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { useTranslations } from "next-intl"
import { Users, AlertTriangle, TrendingUp, FileText, Filter } from "lucide-react"

import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/shared/components/ui/card"
import { Badge } from "@/shared/components/ui/badge"
import { Button } from "@/shared/components/ui/button"
import { Input } from "@/shared/components/ui/input"
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 { usePermission } from "@/shared/hooks"
import { Permissions } from "@/shared/types/permissions"
import { WidgetBoundary } from "@/shared/components/widget-boundary"
import { useDiagnosticService } from "../services/diagnostic-service-context"
import type { ClassMasterySummary } from "../types"

interface ClassDiagnosticViewProps {
  summary: ClassMasterySummary | null
}

/** 掌握度热力图颜色 */
function masteryColor(level: number): string {
  if (level >= 80) return "bg-green-500"
  if (level >= 60) return "bg-yellow-500"
  if (level >= 40) return "bg-orange-500"
  return "bg-red-500"
}

type KnowledgePointStudent = {
  studentId: string
  studentName: string
  masteryLevel: number
  totalQuestions: number
  correctQuestions: number
  lastAssessedAt: string | null
  needsAttention: boolean
}

export function ClassDiagnosticView({ summary }: ClassDiagnosticViewProps) {
  const t = useTranslations("diagnostic")
  const router = useRouter()
  const { hasPermission } = usePermission()
  const canManage = hasPermission(Permissions.DIAGNOSTIC_MANAGE)
  // v2-P1-4: 通过 Context 注入服务，不直接 import actions
  const service = useDiagnosticService()
  const [period, setPeriod] = useState(new Date().toISOString().slice(0, 7))
  const [isGenerating, setIsGenerating] = useState(false)

  // v3-P2-5: 知识点筛选状态
  const [selectedKpId, setSelectedKpId] = useState<string>("all")
  const [filteredStudents, setFilteredStudents] = useState<KnowledgePointStudent[] | null>(null)
  const [isFiltering, setIsFiltering] = useState(false)

  const handleGenerate = async () => {
    if (!summary) return
    setIsGenerating(true)
    const result = await service.generateClassReport(summary.classId, period)
    setIsGenerating(false)
    if (result.success) {
      toast.success(result.message)
      router.refresh()
    } else {
      toast.error(result.message || t("error.generateClassFailed"))
    }
  }

  /**
   * v3-P2-5: 按知识点筛选学生。
   * 选择知识点后调用服务获取该知识点上所有学生的掌握度。
   */
  const handleKpFilter = async (kpId: string) => {
    setSelectedKpId(kpId)
    if (!summary || kpId === "all") {
      setFilteredStudents(null)
      return
    }
    setIsFiltering(true)
    try {
      const result = await service.getClassStudentsByKp(
        summary.classId,
        kpId,
      )
      if (result.success && result.data) {
        setFilteredStudents(result.data)
      } else {
        toast.error(result.message || t("error.loadFailed"))
        setFilteredStudents(null)
      }
    } catch {
      toast.error(t("error.loadFailed"))
      setFilteredStudents(null)
    } finally {
      setIsFiltering(false)
    }
  }

  if (!summary) {
    return (
      <EmptyState
        title={t("classDiagnostic.noClassDataTitle")}
        description={t("empty.noClassData")}
        icon={Users}
        className="border-none shadow-none"
      />
    )
  }

  return (
    <div className="space-y-6">
      {/* v2-P1-6: 概览区块独立 Error Boundary */}
      <WidgetBoundary title={t("summary.class")} skeletonHeight={140}>
        <div className="grid grid-cols-1 gap-4 md:grid-cols-4">
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">{t("summary.class")}</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-2xl font-bold">{summary.className}</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">{t("summary.students")}</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-2xl font-bold">{summary.studentCount}</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">{t("summary.avgMastery")}</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-2xl font-bold">{summary.averageMastery.toFixed(1)}%</p>
            </CardContent>
          </Card>
          <Card>
            <CardHeader className="pb-2">
              <CardTitle className="text-sm font-medium text-muted-foreground">{t("summary.needAttention")}</CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-2xl font-bold text-red-600">{summary.studentsNeedingAttention.length}</p>
            </CardContent>
          </Card>
        </div>
      </WidgetBoundary>

      {/* v2-P1-6: 知识点掌握度热力图区块独立 Error Boundary */}
      <WidgetBoundary title={t("chart.heatmapTitle")} skeletonHeight={300}>
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="h-4 w-4" />
            {t("chart.heatmapTitle")}
          </CardTitle>
          <CardDescription>
            {t("classDiagnostic.heatmapDescription")}
          </CardDescription>
        </CardHeader>
        <CardContent>
          {summary.knowledgePointStats.length === 0 ? (
            <p className="text-sm text-muted-foreground">{t("classDiagnostic.noKnowledgePointData")}</p>
          ) : (
            <>
              <div
                className="flex flex-wrap gap-2"
                role="group"
                aria-label={t("classDiagnostic.heatmapAriaLabel", { count: summary.knowledgePointStats.length })}
              >
                {summary.knowledgePointStats.map((kp) => {
                  const levelLabel = kp.averageMastery >= 80 ? t("classDiagnostic.masteryLevelExcellent") : kp.averageMastery >= 60 ? t("classDiagnostic.masteryLevelGood") : kp.averageMastery >= 40 ? t("classDiagnostic.masteryLevelNeedsImprovement") : t("classDiagnostic.masteryLevelWeak")
                  return (
                    <div
                      key={kp.knowledgePointId}
                      tabIndex={0}
                      className={`flex flex-col items-center justify-center rounded-md px-3 py-2 text-white outline-none transition focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${masteryColor(kp.averageMastery)}`}
                      role="img"
                      aria-label={t("classDiagnostic.heatmapCellAriaLabel", {
                        name: kp.knowledgePointName,
                        level: kp.averageMastery.toFixed(1),
                        label: levelLabel,
                        mastered: kp.masteredCount,
                        total: kp.totalStudents,
                      })}
                      title={`${kp.knowledgePointName}: ${kp.averageMastery.toFixed(1)}% (${kp.masteredCount}/${kp.totalStudents})`}
                    >
                      <span className="max-w-32 truncate text-xs font-medium">
                        {kp.knowledgePointName}
                      </span>
                      <span className="text-sm font-bold">{kp.averageMastery.toFixed(0)}%</span>
                    </div>
                  )
                })}
              </div>
              {/* v4-P1-8: 热力图颜色图例 */}
              <div className="mt-4 flex flex-wrap items-center gap-3 border-t pt-3">
                <span className="text-xs font-medium text-muted-foreground">
                  {t("classDiagnostic.legendLabel")}
                </span>
                <div className="flex flex-wrap items-center gap-3 text-xs">
                  <div className="flex items-center gap-1.5">
                    <span className="inline-block h-3 w-3 rounded-sm bg-green-500" aria-hidden="true" />
                    <span>{t("classDiagnostic.masteryLevelExcellent")} (≥80%)</span>
                  </div>
                  <div className="flex items-center gap-1.5">
                    <span className="inline-block h-3 w-3 rounded-sm bg-yellow-500" aria-hidden="true" />
                    <span>{t("classDiagnostic.masteryLevelGood")} (60-79%)</span>
                  </div>
                  <div className="flex items-center gap-1.5">
                    <span className="inline-block h-3 w-3 rounded-sm bg-orange-500" aria-hidden="true" />
                    <span>{t("classDiagnostic.masteryLevelNeedsImprovement")} (40-59%)</span>
                  </div>
                  <div className="flex items-center gap-1.5">
                    <span className="inline-block h-3 w-3 rounded-sm bg-red-500" aria-hidden="true" />
                    <span>{t("classDiagnostic.masteryLevelWeak")} (&lt;40%)</span>
                  </div>
                </div>
              </div>
            </>
          )}
        </CardContent>
      </Card>
      </WidgetBoundary>

      {/* v2-P1-6: 按知识点筛选学生区块独立 Error Boundary */}
      <WidgetBoundary title={t("classDiagnostic.filterByKpTitle")} skeletonHeight={200}>
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Filter className="h-4 w-4" />
            {t("classDiagnostic.filterByKpTitle")}
          </CardTitle>
          <CardDescription>
            {t("classDiagnostic.filterByKpDescription")}
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="grid gap-2">
            <Label htmlFor="kp-filter" className="text-xs">
              {t("classDiagnostic.kpFilterLabel")}
            </Label>
            <Select value={selectedKpId} onValueChange={handleKpFilter}>
              <SelectTrigger id="kp-filter" className="w-full md:w-80">
                <SelectValue placeholder={t("classDiagnostic.kpFilterPlaceholder")} />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">{t("classDiagnostic.kpFilterAll")}</SelectItem>
                {summary.knowledgePointStats.map((kp) => (
                  <SelectItem key={kp.knowledgePointId} value={kp.knowledgePointId}>
                    {kp.knowledgePointName} ({kp.averageMastery.toFixed(0)}%)
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {isFiltering ? (
            <p className="text-sm text-muted-foreground">{t("classDiagnostic.filtering")}</p>
          ) : filteredStudents && filteredStudents.length > 0 ? (
            <div className="rounded-md border">
              {/* v4-P1-11: 移动端表格水平滚动 */}
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>{t("summary.student")}</TableHead>
                      <TableHead className="text-right">{t("classDiagnostic.avgMasteryColumn")}</TableHead>
                      <TableHead className="text-right">{t("classDiagnostic.totalQuestionsColumn")}</TableHead>
                      <TableHead className="text-right">{t("classDiagnostic.correctQuestionsColumn")}</TableHead>
                      <TableHead>{t("classDiagnostic.statusColumn")}</TableHead>
                      <TableHead></TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {filteredStudents.map((s) => (
                      <TableRow key={s.studentId}>
                        <TableCell className="font-medium">{s.studentName}</TableCell>
                        <TableCell className="text-right font-mono">
                          <Badge variant={s.masteryLevel >= 80 ? "default" : s.masteryLevel >= 60 ? "secondary" : "destructive"}>
                            {s.masteryLevel.toFixed(0)}%
                          </Badge>
                        </TableCell>
                        <TableCell className="text-right">{s.totalQuestions}</TableCell>
                        <TableCell className="text-right">{s.correctQuestions}</TableCell>
                        <TableCell>
                          {s.needsAttention ? (
                            <Badge variant="destructive">{t("classDiagnostic.needsAttention")}</Badge>
                          ) : (
                            <Badge variant="default">{t("classDiagnostic.mastered")}</Badge>
                          )}
                        </TableCell>
                        <TableCell>
                          <Button asChild variant="ghost" size="sm" aria-label={t("classDiagnostic.viewAriaLabel", { studentName: s.studentName })}>
                            <Link href={`/teacher/diagnostic/student/${s.studentId}`}>
                              <FileText className="mr-1 h-3 w-3" />
                              {t("classDiagnostic.viewAction")}
                            </Link>
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </div>
          ) : filteredStudents && filteredStudents.length === 0 ? (
            <p className="text-sm text-muted-foreground">{t("classDiagnostic.noStudentsForKp")}</p>
          ) : null}
        </CardContent>
      </Card>
      </WidgetBoundary>

      {/* v2-P1-6: 知识点排名表区块独立 Error Boundary */}
      <WidgetBoundary title={t("chart.rankingTitle")} skeletonHeight={240}>
      <Card>
        <CardHeader>
          <CardTitle>{t("chart.rankingTitle")}</CardTitle>
        </CardHeader>
        <CardContent>
          {summary.knowledgePointStats.length === 0 ? (
            <p className="text-sm text-muted-foreground">{t("classDiagnostic.noRankingData")}</p>
          ) : (
            <div className="rounded-md border">
              {/* v4-P1-11: 移动端表格水平滚动 */}
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>{t("classDiagnostic.knowledgePointColumn")}</TableHead>
                      <TableHead className="text-right">{t("classDiagnostic.avgMasteryColumn")}</TableHead>
                      <TableHead className="text-right">{t("classDiagnostic.masteredColumn")}</TableHead>
                      <TableHead className="text-right">{t("classDiagnostic.notMasteredColumn")}</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {[...summary.knowledgePointStats]
                      .sort((a, b) => b.averageMastery - a.averageMastery)
                      .map((kp) => (
                        <TableRow key={kp.knowledgePointId}>
                          <TableCell className="font-medium">{kp.knowledgePointName}</TableCell>
                          <TableCell className="text-right font-mono">
                            <Badge variant={kp.averageMastery >= 80 ? "default" : kp.averageMastery >= 60 ? "secondary" : "destructive"}>
                              {kp.averageMastery.toFixed(1)}%
                            </Badge>
                          </TableCell>
                          <TableCell className="text-right text-green-600">{kp.masteredCount}</TableCell>
                          <TableCell className="text-right text-red-600">{kp.notMasteredCount}</TableCell>
                        </TableRow>
                      ))}
                  </TableBody>
                </Table>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
      </WidgetBoundary>

      {/* v2-P1-6: 需重点关注的学生区块独立 Error Boundary */}
      <WidgetBoundary title={t("classDiagnostic.studentsNeedingAttentionTitle")} skeletonHeight={240}>
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <AlertTriangle className="h-4 w-4 text-red-600" />
            {t("classDiagnostic.studentsNeedingAttentionTitle")}
          </CardTitle>
          <CardDescription>{t("classDiagnostic.studentsNeedingAttentionDescription")}</CardDescription>
        </CardHeader>
        <CardContent>
          {summary.studentsNeedingAttention.length === 0 ? (
            <p className="text-sm text-muted-foreground">{t("classDiagnostic.allStudentsAboveThreshold")}</p>
          ) : (
            <div className="rounded-md border">
              {/* v4-P1-11: 移动端表格水平滚动 */}
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>{t("summary.student")}</TableHead>
                      <TableHead className="text-right">{t("classDiagnostic.avgMasteryColumn")}</TableHead>
                      <TableHead className="text-right">{t("classDiagnostic.weakPointsColumn")}</TableHead>
                      <TableHead></TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {summary.studentsNeedingAttention.map((s) => (
                      <TableRow key={s.studentId}>
                        <TableCell className="font-medium">{s.studentName}</TableCell>
                        <TableCell className="text-right">
                          <Badge variant="destructive">{s.averageMastery.toFixed(1)}%</Badge>
                        </TableCell>
                        <TableCell className="text-right text-red-600">{s.weakCount}</TableCell>
                        <TableCell>
                          <Button asChild variant="ghost" size="sm" aria-label={t("classDiagnostic.viewAriaLabel", { studentName: s.studentName })}>
                            <Link href={`/teacher/diagnostic/student/${s.studentId}`}>
                              <FileText className="mr-1 h-3 w-3" />
                              {t("classDiagnostic.viewAction")}
                            </Link>
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
      </WidgetBoundary>

      {/* v2-P1-6: 生成班级报告区块独立 Error Boundary */}
      {canManage ? (
        <WidgetBoundary title={t("report.generateClass")} skeletonHeight={160}>
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileText className="h-4 w-4" />
              {t("report.generateClass")}
            </CardTitle>
            <CardDescription>
              {t("classDiagnostic.generateDescription")}
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex items-end gap-3">
              <div className="grid gap-2">
                <Label htmlFor="class-period" className="text-xs">{t("classDiagnostic.periodLabel")}</Label>
                <Input
                  id="class-period"
                  type="month"
                  value={period}
                  onChange={(e) => setPeriod(e.target.value)}
                  className="w-44"
                />
              </div>
              <Button onClick={handleGenerate} disabled={isGenerating}>
                {isGenerating ? t("classDiagnostic.generating") : t("classDiagnostic.generateButton")}
              </Button>
            </div>
          </CardContent>
        </Card>
        </WidgetBoundary>
      ) : null}
    </div>
  )
}
