"use client"

import { useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Users, AlertTriangle, TrendingUp, FileText } 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 {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/components/ui/table"
import { usePermission } from "@/shared/hooks"
import { Permissions } from "@/shared/types/permissions"
import { generateClassReportAction } from "../actions"
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"
}

export function ClassDiagnosticView({ summary }: ClassDiagnosticViewProps) {
  const router = useRouter()
  const { hasPermission } = usePermission()
  const canManage = hasPermission(Permissions.DIAGNOSTIC_MANAGE)
  const [period, setPeriod] = useState(new Date().toISOString().slice(0, 7))
  const [isGenerating, setIsGenerating] = useState(false)

  const handleGenerate = async () => {
    if (!summary) return
    setIsGenerating(true)
    const formData = new FormData()
    formData.set("classId", summary.classId)
    formData.set("period", period)
    const result = await generateClassReportAction(null, formData)
    setIsGenerating(false)
    if (result.success) {
      toast.success(result.message)
      router.refresh()
    } else {
      toast.error(result.message || "Failed to generate class report")
    }
  }

  if (!summary) {
    return (
      <EmptyState
        title="No class data"
        description="Unable to load class mastery summary."
        icon={Users}
        className="border-none shadow-none"
      />
    )
  }

  return (
    <div className="space-y-6">
      {/* 概览 */}
      <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">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">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">Avg Mastery</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">Need Attention</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-2xl font-bold text-red-600">{summary.studentsNeedingAttention.length}</p>
          </CardContent>
        </Card>
      </div>

      {/* 知识点掌握度热力图 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <TrendingUp className="h-4 w-4" />
            Knowledge Point Mastery Heatmap
          </CardTitle>
          <CardDescription>
            Average mastery level per knowledge point (green ≥80%, yellow 60-79%, orange 40-59%, red &lt;40%).
          </CardDescription>
        </CardHeader>
        <CardContent>
          {summary.knowledgePointStats.length === 0 ? (
            <p className="text-sm text-muted-foreground">No knowledge point data available.</p>
          ) : (
            <div className="flex flex-wrap gap-2">
              {summary.knowledgePointStats.map((kp) => (
                <div
                  key={kp.knowledgePointId}
                  className={`flex flex-col items-center justify-center rounded-md px-3 py-2 text-white ${masteryColor(kp.averageMastery)}`}
                  title={`${kp.knowledgePointName}: ${kp.averageMastery.toFixed(1)}% (mastered ${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>
          )}
        </CardContent>
      </Card>

      {/* 知识点排名表 */}
      <Card>
        <CardHeader>
          <CardTitle>Knowledge Point Ranking</CardTitle>
        </CardHeader>
        <CardContent>
          {summary.knowledgePointStats.length === 0 ? (
            <p className="text-sm text-muted-foreground">No data.</p>
          ) : (
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Knowledge Point</TableHead>
                    <TableHead className="text-right">Avg Mastery</TableHead>
                    <TableHead className="text-right">Mastered (≥80%)</TableHead>
                    <TableHead className="text-right">Not Mastered (&lt;60%)</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>
          )}
        </CardContent>
      </Card>

      {/* 需重点关注的学生 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <AlertTriangle className="h-4 w-4 text-red-600" />
            Students Needing Attention (avg &lt;60%)
          </CardTitle>
          <CardDescription>Students with low overall mastery.</CardDescription>
        </CardHeader>
        <CardContent>
          {summary.studentsNeedingAttention.length === 0 ? (
            <p className="text-sm text-muted-foreground">All students are above the attention threshold.</p>
          ) : (
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Student</TableHead>
                    <TableHead className="text-right">Avg Mastery</TableHead>
                    <TableHead className="text-right">Weak Points</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">
                          <Link href={`/teacher/diagnostic/student/${s.studentId}`}>
                            <FileText className="mr-1 h-3 w-3" />
                            View
                          </Link>
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 生成班级报告 */}
      {canManage ? (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <FileText className="h-4 w-4" />
              Generate Class Diagnostic Report
            </CardTitle>
            <CardDescription>
              Generate a class-level diagnostic report with aggregated analysis.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex items-end gap-3">
              <div className="grid gap-2">
                <Label htmlFor="class-period" className="text-xs">Period (YYYY-MM)</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 ? "Generating..." : "Generate Class Report"}
              </Button>
            </div>
          </CardContent>
        </Card>
      ) : null}
    </div>
  )
}
