"use client"

import { useState } from "react"
import { Area, AreaChart, CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts"
import { ChevronDown } from "lucide-react"
import { useTranslations } from "next-intl"

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/shared/components/ui/card"
import { ChartConfig, ChartContainer, ChartTooltip, ChartTooltipContent } from "@/shared/components/ui/chart"
import { Tabs, TabsList, TabsTrigger } from "@/shared/components/ui/tabs"
import { Button } from "@/shared/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/shared/components/ui/dropdown-menu"

interface AssignmentSummary {
  id: string
  title: string
  status: string
  subject?: string | null
  isActive: boolean
  isOverdue: boolean
  dueAt: Date | null
  submittedCount: number
  targetCount: number
  avgScore: number | null
  medianScore: number | null
}

interface ClassTrendsWidgetProps {
  assignments: AssignmentSummary[]
  compact?: boolean
  className?: string
}

export function transformAssignmentsToChartData(assignments: AssignmentSummary[], limit?: number) {
  const data = [...assignments].reverse().map(a => ({
    title: a.title.length > 10 ? a.title.substring(0, 10) + "..." : a.title,
    fullTitle: a.title,
    submitted: a.submittedCount,
    target: a.targetCount,
    avg: a.avgScore ? Math.round(a.avgScore) : null,
    median: a.medianScore ? Math.round(a.medianScore) : null,
  }))
  
  if (limit) {
    return data.slice(-limit)
  }
  
  return data
}

export function ClassSubmissionTrendChart({
  data,
  className
}: {
  data: Record<string, string | number>[]
  className?: string
}) {
  const t = useTranslations("classes")
  const chartConfig = {
    submitted: { label: t("detail.trends.submitted"), color: "hsl(var(--primary))" },
    target: { label: t("detail.trends.totalStudents"), color: "hsl(var(--muted-foreground))" },
    avg: { label: t("detail.trends.averageScore"), color: "hsl(var(--chart-2))" },
    median: { label: t("detail.trends.medianScore"), color: "hsl(var(--chart-4))" },
  } satisfies ChartConfig
  return (
    <ChartContainer config={chartConfig} className={className}>
      <LineChart accessibilityLayer data={data} margin={{ top: 5, right: 5, bottom: 0, left: 0 }}>
        <CartesianGrid vertical={false} strokeDasharray="3 3" />
        <XAxis
          dataKey="title"
          tickLine={false}
          tickMargin={10}
          axisLine={false}
          fontSize={10}
          hide
        />
        <YAxis
          tickLine={false}
          axisLine={false}
          fontSize={10}
          domain={[0, 'auto']}
          tickFormatter={(value) => `${value}`}
          hide
        />
        <ChartTooltip content={<ChartTooltipContent />} />
        <Line 
          type="monotone" 
          dataKey="target" 
          stroke="var(--color-target)" 
          strokeWidth={2} 
          strokeDasharray="4 4"
          dot={false}
        />
        <Line 
          type="monotone" 
          dataKey="submitted" 
          stroke="var(--color-submitted)" 
          strokeWidth={2} 
          activeDot={{ r: 6 }} 
        />
      </LineChart>
    </ChartContainer>
  )
}

export function ClassTrendsWidget({ assignments, compact, className }: ClassTrendsWidgetProps) {
  const t = useTranslations("classes")
  const chartConfig = {
    submitted: { label: t("detail.trends.submitted"), color: "hsl(var(--primary))" },
    target: { label: t("detail.trends.totalStudents"), color: "hsl(var(--muted-foreground))" },
    avg: { label: t("detail.trends.averageScore"), color: "hsl(var(--chart-2))" },
    median: { label: t("detail.trends.medianScore"), color: "hsl(var(--chart-4))" },
  } satisfies ChartConfig
  const [chartTab, setChartTab] = useState<"submission" | "score">("submission")
  const [selectedSubject, setSelectedSubject] = useState<string>("all")

  // Extract unique subjects
  // P2-A: 使用类型守卫替代 `as string[]`（filter(Boolean) 不会收窄类型是 TS 已知陷阱）
  const subjects = Array.from(new Set(
    assignments.map((a) => a.subject).filter((s): s is string => typeof s === "string")
  ))
  
  const activeAssignments = assignments.filter((a) => {
    if (selectedSubject !== "all" && a.subject !== selectedSubject) return false
    return a.isActive || a.status === "published" // Include published even if not "active" in terms of due date
  })
  
  const chartData = transformAssignmentsToChartData(activeAssignments, 7)

  if (chartData.length === 0 && selectedSubject === "all") return null

  if (compact) {
    // Calculate simple stats for compact view
    const lastAssignment = chartData[chartData.length - 1]
    
    let metricValue = "0%"
    const metricLabel = t("detail.trends.latest")
    
    if (lastAssignment) {
      if (chartTab === "submission") {
        metricValue = lastAssignment.target > 0  
          ? `${Math.round((lastAssignment.submitted / lastAssignment.target) * 100)}%` 
          : "0%"
      } else {
        metricValue = lastAssignment.avg ? `${lastAssignment.avg}` : "-"
      }
    }
    
    return (
      <div className={`flex flex-col h-full ${className || ""}`}>
        <div className="flex items-center justify-between mb-2">
          <div className="flex items-center gap-2">
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" size="sm" className="h-6 gap-1 px-2 text-xs font-semibold text-foreground/80 hover:bg-muted">
                  {chartTab === "submission" ? t("detail.trends.submission") : t("detail.trends.score")}
                  <ChevronDown className="h-3 w-3 opacity-50" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="start">
                <DropdownMenuItem onClick={() => setChartTab("submission")} className="text-xs">
                  {t("detail.widgets.submissionTrends")}
                </DropdownMenuItem>
                <DropdownMenuItem onClick={() => setChartTab("score")} className="text-xs">
                  {t("detail.trends.scoreTrends")}
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>

            {subjects.length > 0 && (
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" size="sm" className="h-6 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground">
                    {selectedSubject === "all" ? t("detail.trends.allSubjects") : selectedSubject}
                    <ChevronDown className="h-3 w-3 opacity-50" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="start">
                  <DropdownMenuItem onClick={() => setSelectedSubject("all")} className="text-xs">
                    {t("detail.trends.allSubjects")}
                  </DropdownMenuItem>
                  {subjects.map(s => (
                    <DropdownMenuItem key={s} onClick={() => setSelectedSubject(s)} className="text-xs">
                      {s}
                    </DropdownMenuItem>
                  ))}
                </DropdownMenuContent>
              </DropdownMenu>
            )}
          </div>
          <div className="text-xs font-medium text-muted-foreground">
            {metricLabel}: <span className="text-foreground">{metricValue}</span>
          </div>
        </div>
        
        {/* Compact Sparkline Chart */}
        <div className="flex-1 w-full min-h-0">
           <ChartContainer config={chartConfig} className="h-full w-full">
             {chartTab === "submission" ? (
               <AreaChart accessibilityLayer data={chartData} margin={{ top: 5, right: 0, bottom: 0, left: 0 }}>
                 <defs>
                   <linearGradient id="fillSubmitted" x1="0" y1="0" x2="0" y2="1">
                     <stop offset="5%" stopColor="var(--color-submitted)" stopOpacity={0.3}/>
                     <stop offset="95%" stopColor="var(--color-submitted)" stopOpacity={0.05}/>
                   </linearGradient>
                 </defs>
                 <CartesianGrid vertical={false} strokeDasharray="3 3" horizontal={false} />
                 <XAxis dataKey="title" hide />
                 <YAxis hide domain={[0, 'auto']} />
                 <ChartTooltip 
                   cursor={false} 
                   content={<ChartTooltipContent indicator="dot" hideLabel />} 
                 />
                 <Area
                   type="monotone"
                   dataKey="submitted"
                   stroke="var(--color-submitted)"
                   fill="url(#fillSubmitted)"
                   strokeWidth={2}
                 />
                 <Line
                   type="monotone"
                   dataKey="target"
                   stroke="var(--color-target)"
                   strokeWidth={1}
                   strokeDasharray="2 2"
                   dot={false}
                   activeDot={false}
                 />
               </AreaChart>
             ) : (
               <LineChart accessibilityLayer data={chartData} margin={{ top: 5, right: 0, bottom: 0, left: 0 }}>
                 <CartesianGrid vertical={false} strokeDasharray="3 3" horizontal={false} />
                 <XAxis dataKey="title" hide />
                 <YAxis hide domain={[0, 100]} />
                 <ChartTooltip 
                   cursor={false} 
                   content={<ChartTooltipContent indicator="dot" />} 
                 />
                 <Line 
                   type="monotone" 
                   dataKey="avg" 
                   stroke="var(--color-avg)" 
                   strokeWidth={2} 
                   dot={false}
                   activeDot={{ r: 4 }} 
                 />
                 <Line 
                   type="monotone" 
                   dataKey="median" 
                   stroke="var(--color-median)" 
                   strokeWidth={2} 
                   strokeDasharray="4 4"
                   dot={false}
                   activeDot={{ r: 4 }} 
                 />
               </LineChart>
             )}
           </ChartContainer>
        </div>
      </div>
    )
  }

  return (
    <Card>
      <CardHeader>
        <div className="flex flex-col gap-4">
          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <CardTitle className="text-base font-semibold">
                {chartTab === "submission" ? t("detail.widgets.submissionTrends") : t("detail.trends.scoreTrends")}
              </CardTitle>
              <CardDescription>
                {chartTab === "submission" ? t("detail.trends.recentTurnInRates") : t("detail.trends.avgVsMedian")}
              </CardDescription>
            </div>
            <Tabs value={chartTab} onValueChange={(v) => setChartTab(v as "submission" | "score")} className="w-auto">
              <TabsList className="grid w-full grid-cols-2 h-8">
                <TabsTrigger value="submission" className="text-xs">{t("detail.trends.submission")}</TabsTrigger>
                <TabsTrigger value="score" className="text-xs">{t("detail.trends.score")}</TabsTrigger>
              </TabsList>
            </Tabs>
          </div>

          {subjects.length > 0 && (
             <Tabs value={selectedSubject} onValueChange={setSelectedSubject} className="w-full">
               <TabsList className="h-8 w-auto flex-wrap justify-start bg-transparent p-0">
                 <TabsTrigger
                   value="all"
                   className="h-7 rounded-md border bg-background px-3 text-xs data-[state=active]:bg-muted data-[state=active]:text-foreground"
                 >
                   {t("detail.trends.allSubjects")}
                 </TabsTrigger>
                 {subjects.map(s => (
                   <TabsTrigger 
                     key={s} 
                     value={s} 
                     className="ml-2 h-7 rounded-md border bg-background px-3 text-xs data-[state=active]:bg-muted data-[state=active]:text-foreground"
                   >
                     {s}
                   </TabsTrigger>
                 ))}
               </TabsList>
             </Tabs>
          )}
        </div>
      </CardHeader>
      <CardContent>
        {chartData.length > 0 ? (
        <ChartContainer config={chartConfig} className="h-[250px] w-full">
          {chartTab === "submission" ? (
            <LineChart accessibilityLayer data={chartData} margin={{ top: 20, right: 20, bottom: 0, left: 0 }}>
              <CartesianGrid vertical={false} strokeDasharray="3 3" />
              <XAxis
                dataKey="title"
                tickLine={false}
                tickMargin={10}
                axisLine={false}
                fontSize={12}
              />
              <YAxis
                tickLine={false}
                axisLine={false}
                fontSize={12}
                domain={[0, 'auto']}
                tickFormatter={(value) => `${value}`}
              />
              <ChartTooltip content={<ChartTooltipContent />} />
              <Line 
                type="monotone" 
                dataKey="target" 
                stroke="var(--color-target)" 
                strokeWidth={2} 
                strokeDasharray="4 4"
                dot={false}
              />
              <Line 
                type="monotone" 
                dataKey="submitted" 
                stroke="var(--color-submitted)" 
                strokeWidth={2} 
                activeDot={{ r: 6 }} 
              />
            </LineChart>
          ) : (
            <LineChart accessibilityLayer data={chartData} margin={{ top: 20, right: 20, bottom: 0, left: 0 }}>
              <CartesianGrid vertical={false} strokeDasharray="3 3" />
              <XAxis
                dataKey="title"
                tickLine={false}
                tickMargin={10}
                axisLine={false}
                fontSize={12}
              />
              <YAxis
                tickLine={false}
                axisLine={false}
                fontSize={12}
                domain={[0, 100]}
                tickFormatter={(value) => `${value}%`}
              />
              <ChartTooltip content={<ChartTooltipContent />} />
              <Line 
                type="monotone" 
                dataKey="avg" 
                stroke="var(--color-avg)" 
                strokeWidth={2} 
                activeDot={{ r: 6 }} 
              />
              <Line 
                type="monotone" 
                dataKey="median" 
                stroke="var(--color-median)" 
                strokeWidth={2} 
                strokeDasharray="4 4"
                activeDot={{ r: 6 }} 
              />
            </LineChart>
          )}
        </ChartContainer>
        ) : (
          <div className="flex h-[250px] items-center justify-center text-sm text-muted-foreground">
            {t("detail.trends.noDataForSubject")}
          </div>
        )}
      </CardContent>
    </Card>
  )
}
