import { useAuth } from "@/_core/hooks/useAuth";
import { trpc } from "@/lib/trpc";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Skeleton } from "@/components/ui/skeleton";
import { Award, TrendingUp, Target, Zap, Footprints, Activity, Wind } from "lucide-react";
import {
  ResponsiveContainer, RadarChart, PolarGrid, PolarAngleAxis,
  PolarRadiusAxis, Radar, AreaChart, Area, XAxis, YAxis,
  CartesianGrid, Tooltip, Legend
} from "recharts";

const NTRP_LEVELS = [
  { min: 1.0, max: 1.5, label: "初学者", desc: "刚开始学习网球，正在学习基本击球动作", color: "bg-gray-100 text-gray-700" },
  { min: 1.5, max: 2.0, label: "初级", desc: "能够进行简单的来回击球，但缺乏一致性", color: "bg-orange-100 text-orange-700" },
  { min: 2.0, max: 2.5, label: "初中级", desc: "击球更加稳定，开始理解基本策略", color: "bg-yellow-100 text-yellow-700" },
  { min: 2.5, max: 3.0, label: "中级", desc: "能够稳定地进行中速击球，具备基本的网前技术", color: "bg-green-100 text-green-700" },
  { min: 3.0, max: 3.5, label: "中高级", desc: "击球力量和控制力增强，开始使用旋转", color: "bg-blue-100 text-blue-700" },
  { min: 3.5, max: 4.0, label: "高级", desc: "具备全面的技术，能够在比赛中运用战术", color: "bg-indigo-100 text-indigo-700" },
  { min: 4.0, max: 4.5, label: "高级竞技", desc: "技术精湛，具备强大的进攻和防守能力", color: "bg-purple-100 text-purple-700" },
  { min: 4.5, max: 5.0, label: "专业水平", desc: "接近职业水平，全面的技术和战术能力", color: "bg-red-100 text-red-700" },
];

function getNTRPLevel(rating: number) {
  return NTRP_LEVELS.find(l => rating >= l.min && rating < l.max) || NTRP_LEVELS[0];
}

export default function Rating() {
  const { user } = useAuth();
  const { data: ratingData } = trpc.rating.current.useQuery();
  const { data: history, isLoading } = trpc.rating.history.useQuery();
  const { data: stats } = trpc.profile.stats.useQuery();

  const currentRating = ratingData?.rating || 1.5;
  const level = getNTRPLevel(currentRating);

  // Get latest dimension scores
  const latestWithDimensions = history?.find((h: any) => h.dimensionScores);
  const dimensions = (latestWithDimensions as any)?.dimensionScores || {};

  const radarData = [
    { dimension: "姿势准确", value: dimensions.poseAccuracy || 0, fullMark: 100 },
    { dimension: "击球一致", value: dimensions.strokeConsistency || 0, fullMark: 100 },
    { dimension: "脚步移动", value: dimensions.footwork || 0, fullMark: 100 },
    { dimension: "动作流畅", value: dimensions.fluidity || 0, fullMark: 100 },
    { dimension: "力量", value: dimensions.power || 0, fullMark: 100 },
  ];

  const trendData = (history || []).map((h: any) => ({
    date: new Date(h.createdAt).toLocaleDateString("zh-CN", { month: "short", day: "numeric" }),
    rating: h.rating,
  }));

  if (isLoading) {
    return (
      <div className="space-y-4">
        <Skeleton className="h-40 w-full" />
        <Skeleton className="h-60 w-full" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">NTRP评分系统</h1>
        <p className="text-muted-foreground text-sm mt-1">基于所有历史训练记录自动计算的综合评分</p>
      </div>

      {/* Current rating card */}
      <Card className="border-0 shadow-sm overflow-hidden">
        <div className="bg-gradient-to-r from-primary/10 via-primary/5 to-transparent p-6">
          <div className="flex flex-col sm:flex-row sm:items-center gap-6">
            <div className="flex items-center gap-4">
              <div className="h-20 w-20 rounded-2xl bg-primary/10 flex items-center justify-center">
                <span className="text-3xl font-bold text-primary">{currentRating.toFixed(1)}</span>
              </div>
              <div>
                <h2 className="text-xl font-bold">{level.label}</h2>
                <p className="text-sm text-muted-foreground mt-1 max-w-md">{level.desc}</p>
                <div className="flex items-center gap-2 mt-2">
                  <Award className="h-4 w-4 text-primary" />
                  <span className="text-sm font-medium">NTRP {currentRating.toFixed(1)}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </Card>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Radar chart */}
        <Card className="border-0 shadow-sm">
          <CardHeader className="pb-2">
            <CardTitle className="text-base flex items-center gap-2">
              <Target className="h-4 w-4 text-primary" />
              能力雷达图
            </CardTitle>
            <CardDescription>五维度综合能力评估</CardDescription>
          </CardHeader>
          <CardContent>
            {Object.keys(dimensions).length > 0 ? (
              <ResponsiveContainer width="100%" height={280}>
                <RadarChart data={radarData}>
                  <PolarGrid stroke="#e5e7eb" />
                  <PolarAngleAxis dataKey="dimension" tick={{ fontSize: 12 }} />
                  <PolarRadiusAxis angle={90} domain={[0, 100]} tick={{ fontSize: 10 }} />
                  <Radar
                    name="能力值"
                    dataKey="value"
                    stroke="oklch(0.55 0.16 145)"
                    fill="oklch(0.55 0.16 145)"
                    fillOpacity={0.3}
                    strokeWidth={2}
                  />
                </RadarChart>
              </ResponsiveContainer>
            ) : (
              <div className="h-[280px] flex items-center justify-center text-muted-foreground text-sm">
                <div className="text-center">
                  <Target className="h-8 w-8 mx-auto mb-2 opacity-30" />
                  <p>完成视频分析后将显示能力雷达图</p>
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Rating trend */}
        <Card className="border-0 shadow-sm">
          <CardHeader className="pb-2">
            <CardTitle className="text-base flex items-center gap-2">
              <TrendingUp className="h-4 w-4 text-primary" />
              评分变化趋势
            </CardTitle>
            <CardDescription>NTRP评分随时间的变化</CardDescription>
          </CardHeader>
          <CardContent>
            {trendData.length > 0 ? (
              <ResponsiveContainer width="100%" height={280}>
                <AreaChart data={trendData}>
                  <defs>
                    <linearGradient id="ratingGrad" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="oklch(0.55 0.16 145)" stopOpacity={0.3} />
                      <stop offset="95%" stopColor="oklch(0.55 0.16 145)" stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
                  <XAxis dataKey="date" tick={{ fontSize: 11 }} />
                  <YAxis domain={[1, 5]} tick={{ fontSize: 11 }} />
                  <Tooltip />
                  <Area type="monotone" dataKey="rating" stroke="oklch(0.55 0.16 145)" fill="url(#ratingGrad)" strokeWidth={2} />
                </AreaChart>
              </ResponsiveContainer>
            ) : (
              <div className="h-[280px] flex items-center justify-center text-muted-foreground text-sm">
                <div className="text-center">
                  <TrendingUp className="h-8 w-8 mx-auto mb-2 opacity-30" />
                  <p>完成视频分析后将显示评分趋势</p>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Dimension details */}
      <Card className="border-0 shadow-sm">
        <CardHeader className="pb-2">
          <CardTitle className="text-base">评分维度说明</CardTitle>
          <CardDescription>NTRP评分由以下五个维度加权计算</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4">
            {[
              { icon: Target, label: "姿势准确性", weight: "30%", desc: "关节角度与标准动作的匹配度", value: dimensions.poseAccuracy },
              { icon: Zap, label: "击球一致性", weight: "25%", desc: "多次击球动作的稳定性", value: dimensions.strokeConsistency },
              { icon: Footprints, label: "脚步移动", weight: "20%", desc: "步法灵活性和重心转移", value: dimensions.footwork },
              { icon: Wind, label: "动作流畅性", weight: "15%", desc: "动作连贯性和平滑度", value: dimensions.fluidity },
              { icon: Activity, label: "力量", weight: "10%", desc: "挥拍速度和爆发力", value: dimensions.power },
            ].map(item => (
              <div key={item.label} className="p-4 rounded-xl border bg-card">
                <div className="flex items-center gap-2 mb-2">
                  <item.icon className="h-4 w-4 text-primary" />
                  <span className="text-sm font-medium">{item.label}</span>
                </div>
                <p className="text-2xl font-bold">{item.value ? Math.round(item.value) : "--"}</p>
                <p className="text-xs text-muted-foreground mt-1">权重 {item.weight}</p>
                <p className="text-xs text-muted-foreground">{item.desc}</p>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* NTRP level reference */}
      <Card className="border-0 shadow-sm">
        <CardHeader className="pb-2">
          <CardTitle className="text-base">NTRP等级参考</CardTitle>
          <CardDescription>美国网球协会(USTA)标准评级体系</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-2">
            {NTRP_LEVELS.map(l => (
              <div
                key={l.label}
                className={`flex items-center gap-3 p-3 rounded-lg transition-colors ${
                  currentRating >= l.min && currentRating < l.max
                    ? "bg-primary/5 border border-primary/20"
                    : "hover:bg-muted/50"
                }`}
              >
                <Badge className={`${l.color} border shrink-0`}>
                  {l.min.toFixed(1)}-{l.max.toFixed(1)}
                </Badge>
                <div>
                  <span className="text-sm font-medium">{l.label}</span>
                  <p className="text-xs text-muted-foreground">{l.desc}</p>
                </div>
                {currentRating >= l.min && currentRating < l.max && (
                  <Badge variant="default" className="ml-auto shrink-0">当前等级</Badge>
                )}
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
