"use client";

import {
  TrendingUp,
  Download,
  Info,
  CheckCircle2,
  AlertTriangle,
  User,
} from "lucide-react";
import { useSearchParams } from "next/navigation";
import { metricsData } from "./metricsData";
import { getMockStudentById } from "@/lib/mockApi";
import { useAuth } from "@/components/AuthProvider";

export default function MetricsContent({ metricId }: { metricId: string }) {
  const searchParams = useSearchParams();
  const { user } = useAuth();
  
  const studentId = searchParams.get("student") || (user?.role === 'stu' ? user.id : null);
  const student = studentId ? getMockStudentById(studentId) : null;

  const categoryStr = metricId.charAt(0).toUpperCase();
  const metricCategoryList = metricsData[categoryStr] || [];
  const metricObj = metricCategoryList.find(m => m.id === metricId.toUpperCase());

  if (!metricObj) {
    return (
      <div className="flex-grow flex items-center justify-center p-8">
        <h2 className="text-xl text-secondary">未找到指标 {metricId.toUpperCase()} 的详情</h2>
      </div>
    );
  }

  // When viewing a specific student, use their pre-generated score for this metric.
  // Otherwise use the static class average from metricsData.
  let scoreNum = parseFloat(metricObj.avgScore) || 85.0;
  if (student) {
    const storedScore = student.metricScores?.[metricId.toUpperCase()];
    if (storedScore !== undefined) {
      scoreNum = storedScore;
    }
  }

  return (
    <main className="flex-grow p-4 md:p-8 max-w-7xl mx-auto w-full grid grid-cols-1 lg:grid-cols-12 gap-6">
      <aside className="lg:col-span-4 xl:col-span-3 space-y-6">
        <div className="bg-surface rounded-2xl p-6 shadow-elevation-1 border border-outline-variant">
          <div className="flex items-center gap-2 mb-4">
            <span className={`w-2 h-8 rounded-full bg-${metricObj.colorClass}`}></span>
            <h2 className="text-lg font-medium text-on-surface">
              {metricObj.id} - {metricObj.name}
            </h2>
          </div>
          <div className="flex flex-col items-center justify-center py-8 relative">
            {/* Ambient Background Glow */}
            <div 
              className="absolute w-40 h-40 rounded-full opacity-20 blur-2xl"
              style={{ backgroundColor: `var(--color-${metricObj.colorClass})` }}
            ></div>
            
            <div className="relative w-40 h-40 flex items-center justify-center rounded-full bg-surface shadow-elevation-2 border border-outline-variant/30">
              <svg
                className="absolute w-full h-full transform -rotate-90 drop-shadow-md"
                viewBox="0 0 100 100"
              >
                {/* Track Circle */}
                <circle
                  cx="50"
                  cy="50"
                  r="44"
                  fill="transparent"
                  className="stroke-surface-variant flex-shrink-0"
                  strokeWidth="6"
                />
                {/* Progress Circle */}
                <circle
                  cx="50"
                  cy="50"
                  fill="transparent"
                  r="44"
                  style={{ stroke: `var(--color-${metricObj.colorClass})` }}
                  strokeDasharray={`${(scoreNum / 100) * 276.46} 276.46`}
                  strokeDashoffset="0"
                  strokeLinecap="round"
                  strokeWidth="8"
                  className="transition-all duration-1000 ease-out"
                ></circle>
              </svg>
              <div className="text-center z-10 flex flex-col items-center justify-center bg-surface w-28 h-28 rounded-full shadow-inner border border-outline-variant/10">
                <span 
                  className="text-4xl font-display font-bold tracking-tight"
                  style={{ color: `var(--color-${metricObj.colorClass})` }}
                >
                  {scoreNum}
                </span>
                <span className="block text-[0.65rem] text-on-surface-variant uppercase tracking-widest mt-1 font-medium">
                  得分
                </span>
              </div>
            </div>
          </div>
          <div className="space-y-4 mt-2">
            <div className="flex justify-between items-center text-sm">
              <span className="text-on-surface-variant">
                趋势 (对比上月)
              </span>
              <span className="flex items-center text-metric-high font-medium bg-metric-high/10 px-2 py-0.5 rounded-md">
                <TrendingUp className="w-4 h-4 mr-1" /> +2.1%
              </span>
            </div>
          </div>
          <div className="mt-6 pt-6 border-t border-outline-variant">
            <button className="w-full bg-primary text-on-primary h-10 rounded-full font-medium text-sm shadow-md hover:shadow-lg transition-all flex items-center justify-center gap-2 cursor-pointer">
              <Download className="w-5 h-5" /> 导出报告
            </button>
          </div>
        </div>
        <div className={`${metricObj.bgClass} rounded-2xl p-6`}>
          <h3 className="font-medium mb-2 flex items-center gap-2">
            <Info className="w-5 h-5" /> 指标说明
          </h3>
          <p className="text-sm opacity-90 leading-relaxed font-light">
            {metricObj.description}
          </p>
        </div>
      </aside>

      <section className="lg:col-span-8 xl:col-span-9 space-y-6">
        <div className="flex flex-col md:flex-row md:items-center justify-between mb-2">
          <div>
            <h2 className="text-2xl font-medium text-on-background">
              子指标分析
            </h2>
            <p className="text-on-surface-variant text-sm mt-1">
              关于 {metricObj.id} 的详细数据维度拆解
            </p>
          </div>
          <div className="flex gap-2 mt-4 md:mt-0">
            <button className="h-10 px-4 rounded-full border border-outline text-on-surface-variant text-sm font-medium hover:bg-surface-variant hover:text-on-surface focus:ring-2 focus:ring-primary focus:outline-none transition-colors cursor-pointer">
              筛选
            </button>
            <button className="h-10 px-4 rounded-full border border-outline text-on-surface-variant text-sm font-medium hover:bg-surface-variant hover:text-on-surface focus:ring-2 focus:ring-primary focus:outline-none transition-colors cursor-pointer">
              日期范围
            </button>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {metricObj.subMetrics.map((sub, i) => {
            // Generating some mock variation to make UI look realistic
            const subScore = Math.min(100, scoreNum + ((i % 3 === 0 ? 1 : -1) * (i * 2 + 3)));
            const isWarn = subScore < 80;
            
            return (
              <article key={sub.id} className="bg-surface rounded-xl p-0 shadow-elevation-1 border border-outline-variant overflow-hidden flex flex-col h-full hover:shadow-elevation-2 hover:bg-surface-container transition-all duration-300 group">
                <div className="p-5 border-b border-outline-variant bg-surface-variant/20">
                  <div className="flex justify-between items-start">
                    <div>
                      <span className={`text-xs font-bold tracking-wider uppercase text-${metricObj.colorClass}`}>
                        {sub.id}
                      </span>
                      <h3 className="text-lg font-medium text-on-surface mt-1">
                        {sub.name}
                      </h3>
                    </div>
                    <span className={`w-8 h-8 rounded-full flex items-center justify-center ${isWarn ? 'bg-metric-warn/10 text-metric-warn' : 'bg-metric-high/10 text-metric-high'}`}>
                      {isWarn ? <AlertTriangle className="w-5 h-5" /> : <CheckCircle2 className="w-5 h-5" />}
                    </span>
                  </div>
                </div>
                <div className="p-5 flex-grow space-y-5">
                  {sub.values.map((val, idx) => (
                    <div key={idx} className="flex flex-col gap-1">
                      <div className="flex items-center justify-between">
                         <div className="flex items-start gap-3">
                           <CheckCircle2 className="text-on-surface-variant w-5 h-5 mt-0.5" />
                           <p className="text-sm font-medium text-on-surface leading-tight">
                             {val.name}
                           </p>
                         </div>
                         <div className="text-right whitespace-nowrap ml-2">
                           <span className={`block text-xl font-bold ${isWarn ? 'text-metric-warn' : 'text-metric-high'}`}>
                             {idx === 0 ? subScore + '%' : (isWarn ? '一般' : '优秀')}
                           </span>
                         </div>
                      </div>
                    </div>
                  ))}
                  <div className="w-full bg-surface-variant rounded-full h-1.5 mt-2">
                    <div
                      className={`h-1.5 rounded-full ${isWarn ? 'bg-metric-warn' : 'bg-metric-high'}`}
                      style={{ width: `${subScore}%` }}
                    ></div>
                  </div>
                </div>
                <div className="px-5 py-3 bg-surface-variant/10 flex justify-end border-t border-outline-variant/50">
                  <button className="text-primary text-sm font-medium hover:bg-primary/10 px-3 py-1.5 rounded-lg transition-colors cursor-pointer">
                    查看详情
                  </button>
                </div>
              </article>
            );
          })}
        </div>
      </section>
    </main>
  );
}
