"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Award, AlertTriangle, Lightbulb, FileText, TrendingUp } 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 { usePermission } from "@/shared/hooks"
import { Permissions } from "@/shared/types/permissions"
import { MasteryRadarChart } from "./mastery-radar-chart"
import { generateStudentReportAction } from "../actions"
import type { DiagnosticReportWithDetails, MasteryRadarPoint, StudentMasterySummary } from "../types"

interface StudentDiagnosticViewProps {
  summary: StudentMasterySummary | null
  reports: DiagnosticReportWithDetails[]
  classAverageMastery?: MasteryRadarPoint[]
}

export function StudentDiagnosticView({ summary, reports, classAverageMastery }: StudentDiagnosticViewProps) {
  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("studentId", summary.studentId)
    formData.set("period", period)
    const result = await generateStudentReportAction(null, formData)
    setIsGenerating(false)
    if (result.success) {
      toast.success(result.message)
      router.refresh()
    } else {
      toast.error(result.message || "Failed to generate report")
    }
  }

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

  const radarData: MasteryRadarPoint[] = summary.allMastery.map((m) => {
    const classAvg = classAverageMastery?.find((c) => c.knowledgePoint === m.knowledgePointName)
    return {
      knowledgePoint: m.knowledgePointName,
      student: Math.round(m.masteryLevel * 100) / 100,
      classAverage: classAvg?.classAverage,
    }
  })

  const publishedReports = reports.filter((r) => r.status === "published")
  const latestReport = publishedReports[0] ?? reports[0] ?? null

  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">Student</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-2xl font-bold">{summary.studentName}</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Overall 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">Strengths</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-2xl font-bold text-green-600">{summary.strengths.length}</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium text-muted-foreground">Weaknesses</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-2xl font-bold text-red-600">{summary.weaknesses.length}</p>
          </CardContent>
        </Card>
      </div>

      {/* 雷达图 */}
      <MasteryRadarChart data={radarData} />

      {/* 强项 / 弱项 */}
      <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Award className="h-4 w-4 text-green-600" />
              Strengths (≥80%)
            </CardTitle>
            <CardDescription>Knowledge points with high mastery.</CardDescription>
          </CardHeader>
          <CardContent>
            {summary.strengths.length === 0 ? (
              <p className="text-sm text-muted-foreground">No strengths identified yet.</p>
            ) : (
              <ul className="space-y-2">
                {summary.strengths.map((m) => (
                  <li key={m.knowledgePointId} className="flex items-center justify-between">
                    <span className="text-sm">{m.knowledgePointName}</span>
                    <Badge variant="default" className="bg-green-600">{m.masteryLevel.toFixed(1)}%</Badge>
                  </li>
                ))}
              </ul>
            )}
          </CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <AlertTriangle className="h-4 w-4 text-red-600" />
              Weaknesses (&lt;60%)
            </CardTitle>
            <CardDescription>Knowledge points needing attention.</CardDescription>
          </CardHeader>
          <CardContent>
            {summary.weaknesses.length === 0 ? (
              <p className="text-sm text-muted-foreground">No weaknesses identified.</p>
            ) : (
              <ul className="space-y-2">
                {summary.weaknesses.map((m) => (
                  <li key={m.knowledgePointId} className="flex items-center justify-between">
                    <span className="text-sm">{m.knowledgePointName}</span>
                    <Badge variant="destructive">{m.masteryLevel.toFixed(1)}%</Badge>
                  </li>
                ))}
              </ul>
            )}
          </CardContent>
        </Card>
      </div>

      {/* 生成报告 */}
      {canManage ? (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <TrendingUp className="h-4 w-4" />
              Generate Diagnostic Report
            </CardTitle>
            <CardDescription>
              Generate an AI-analyzed diagnostic report for this student.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex items-end gap-3">
              <div className="grid gap-2">
                <Label htmlFor="period" className="text-xs">Period (YYYY-MM)</Label>
                <Input
                  id="period"
                  type="month"
                  value={period}
                  onChange={(e) => setPeriod(e.target.value)}
                  className="w-[180px]"
                />
              </div>
              <Button onClick={handleGenerate} disabled={isGenerating}>
                {isGenerating ? "Generating..." : "Generate Report"}
              </Button>
            </div>
          </CardContent>
        </Card>
      ) : null}

      {/* 最新报告 / 建议 */}
      {latestReport ? (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Lightbulb className="h-4 w-4" />
              Diagnostic Report
              <Badge variant={latestReport.status === "published" ? "default" : "secondary"}>
                {latestReport.status}
              </Badge>
            </CardTitle>
            <CardDescription>
              Period: {latestReport.period ?? "-"} · Overall: {latestReport.overallScore?.toFixed(1) ?? "-"}%
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {latestReport.summary ? (
              <p className="text-sm">{latestReport.summary}</p>
            ) : null}
            {latestReport.recommendations && latestReport.recommendations.length > 0 ? (
              <div>
                <h4 className="mb-2 text-sm font-semibold">Recommendations</h4>
                <ul className="space-y-1.5">
                  {latestReport.recommendations.map((rec, i) => (
                    <li key={i} className="text-sm text-muted-foreground">• {rec}</li>
                  ))}
                </ul>
              </div>
            ) : null}
          </CardContent>
        </Card>
      ) : null}
    </div>
  )
}
