"use client";

import { useState } from "react";
import { Download, ChevronDown, CheckCircle2 } from "lucide-react";
import Link from "next/link";
import { metricsData, MetricCategoryData } from "./metricsData";

export default function DashboardContent() {
  const [expandedCard, setExpandedCard] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState<"K" | "A" | "S" | "D">("K");

  const toggleCard = (id: string) => {
    setExpandedCard(expandedCard === id ? null : id);
  };

  const getMetricStatus = (score: string) => {
    const num = parseInt(score);
    if (isNaN(num)) return { label: "未知", class: "bg-surface-variant text-on-surface-variant" };
    if (num >= 90) return { label: "优秀", class: "bg-metric-high/10 text-metric-high border-metric-high/30" };
    if (num >= 80) return { label: "良好", class: "bg-metric-mid/10 text-metric-mid border-metric-mid/30" };
    if (num >= 70) return { label: "一般", class: "bg-metric-warn/10 text-metric-warn border-metric-warn/30" };
    return { label: "需改进", class: "bg-metric-low/10 text-metric-low border-metric-low/30" };
  };

  return (
    <div className="flex-1 overflow-y-auto p-4 lg:p-8 space-y-6">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-end mb-2">
        <div>
          <h1 className="text-3xl lg:text-4xl font-display font-medium text-on-surface mb-1">
            综合能力总览
          </h1>
          <p className="text-secondary text-sm lg:text-base">
            基于核心能力指标的数据分析与追踪
          </p>
        </div>
        <div className="mt-4 md:mt-0 flex gap-3">
          <button className="flex items-center px-5 py-2.5 bg-primary text-on-primary rounded-full shadow-lg hover:shadow-primary/20 hover:bg-white transition-all font-medium text-sm cursor-pointer">
            <Download className="w-5 h-5 mr-2" />
            导出报告
          </button>
        </div>
      </div>

      <div>
        <nav
          aria-label="Tabs"
          className="flex space-x-6 overflow-x-auto pb-1 no-scrollbar"
        >
          <button 
            onClick={() => setActiveTab("K")}
            className={`whitespace-nowrap py-3 px-2 border-b-2 font-medium text-sm transition-colors cursor-pointer ${activeTab === 'K' ? 'border-primary text-primary' : 'border-transparent text-secondary hover:text-on-surface hover:border-outline'}`}
          >
            知识掌握情况 (K)
          </button>
          <button 
            onClick={() => setActiveTab("A")}
            className={`whitespace-nowrap py-3 px-2 border-b-2 font-medium text-sm transition-colors cursor-pointer ${activeTab === 'A' ? 'border-primary text-primary' : 'border-transparent text-secondary hover:text-on-surface hover:border-outline'}`}
          >
            AI 辅助能力 (A)
          </button>
          <button 
            onClick={() => setActiveTab("S")}
            className={`whitespace-nowrap py-3 px-2 border-b-2 font-medium text-sm transition-colors cursor-pointer ${activeTab === 'S' ? 'border-primary text-primary' : 'border-transparent text-secondary hover:text-on-surface hover:border-outline'}`}
          >
            软件工程能力 (S)
          </button>
          <button 
            onClick={() => setActiveTab("D")}
            className={`whitespace-nowrap py-3 px-2 border-b-2 font-medium text-sm transition-colors cursor-pointer ${activeTab === 'D' ? 'border-primary text-primary' : 'border-transparent text-secondary hover:text-on-surface hover:border-outline'}`}
          >
            态度与团队协作 (D)
          </button>
        </nav>
      </div>

      <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
        {metricsData[activeTab].map((metric) => (
          <div
            key={metric.id}
            className={`bg-surface-container rounded-3xl p-6 shadow-elevation-1 hover:shadow-elevation-2 transition-all border border-outline-variant/50 group cursor-pointer ${expandedCard === metric.id ? "expanded" : ""}`}
            onClick={() => toggleCard(metric.id)}
          >
            <div className="flex justify-between items-start">
              <div className="flex items-center gap-4">
                <div className={`h-14 w-14 rounded-2xl flex items-center justify-center ${metric.bgClass}`}>
                  <span className="font-bold text-xl">
                    {metric.id}
                  </span>
                </div>
                <div>
                  <h3 className={`text-lg font-medium text-on-surface transition-colors group-hover:${metric.textClass}`}>
                    {metric.name}
                  </h3>
                  <p className="text-sm text-secondary">
                    {metric.description}
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-4">
                <div className="text-right hidden sm:block">
                  <div className={`text-2xl font-bold text-${metric.colorClass}`}>{metric.avgScore}</div>
                  <div className="text-xs text-secondary">平均分</div>
                </div>
                <ChevronDown
                  className={`w-6 h-6 text-secondary transition-transform duration-300 ${expandedCard === metric.id ? "rotate-180" : ""}`}
                />
              </div>
            </div>
            <div className="mt-5 w-full bg-surface-container-high rounded-full h-2 overflow-hidden">
              <div
                className={`h-2 rounded-full`}
                style={{ width: metric.avgScore, backgroundColor: `var(--color-${metric.colorClass})` }}
              ></div>
            </div>
            <div className={`mt-0 border-t border-outline-variant/30 pt-0 ${expandedCard === metric.id ? "animate-in slide-in-from-top-2 block" : "hidden"}`}>
              <div className="pt-6 space-y-6">
                {metric.subMetrics.map((subMetric) => {
                  // Make a fake consistent status based on submetric ID string length and char codes for visual diversity, in a real app this is data driven
                  const fakeScoreVal = 70 + (subMetric.id.charCodeAt(subMetric.id.length - 1) * 3) % 25; 
                  const status = getMetricStatus(fakeScoreVal.toString());
                  
                  return (
                    <div key={subMetric.id}>
                      <div className="flex justify-between items-center mb-3">
                        <h4 className="font-medium text-sm text-on-surface">
                          {subMetric.id} {subMetric.name}
                        </h4>
                        <span className={`text-xs font-bold border px-2 py-0.5 rounded-full ${status.class}`}>
                          {status.label}
                        </span>
                      </div>
                      <div className="grid gap-2">
                        {subMetric.values.map((val, idx) => (
                           <div key={idx} className="flex items-center justify-between text-sm p-3 rounded-lg bg-surface-container-high border border-outline-variant/20 transition-colors">
                              <div className="flex items-center text-secondary">
                                <CheckCircle2 className={`w-4 h-4 mr-3 text-${metric.colorClass}`} />
                                {val.name}
                              </div>
                           </div>
                        ))}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-8 mb-4">
        <h2 className="text-xl font-display font-medium text-on-secondary-container">
          近期活动追踪
        </h2>
      </div>

      <div className="bg-surface-container rounded-3xl p-0 shadow-elevation-1 overflow-hidden border border-outline-variant/50">
        <div className="overflow-x-auto">
          <table className="w-full text-left border-collapse">
            <thead>
              <tr className="bg-surface-container-high border-b border-outline-variant/30">
                <th className="p-4 font-medium text-sm text-secondary uppercase tracking-wider">
                  能力指标
                </th>
                <th className="p-4 font-medium text-sm text-secondary uppercase tracking-wider">
                  测验/活动
                </th>
                <th className="p-4 font-medium text-sm text-secondary uppercase tracking-wider">
                  得分
                </th>
                <th className="p-4 font-medium text-sm text-secondary uppercase tracking-wider">
                  状态
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-outline-variant/20">
              {metricsData[activeTab].slice(0, 4).map((metric, i) => {
                 const status = getMetricStatus(metric.avgScore);
                 return (
                  <tr
                    key={i}
                    className="hover:bg-white/5 transition-colors cursor-pointer"
                    onClick={() => (window.location.href = `/metrics/${metric.id.toLowerCase()}`)}
                  >
                    <td className="p-4">
                      <span className={`font-bold px-2 py-1 rounded text-xs mr-2 ${metric.bgClass}`}>
                        {metric.id}
                      </span>
                      <span className="text-on-surface">{metric.name}</span>
                    </td>
                    <td className="p-4 text-sm text-secondary">
                      {metric.subMetrics[0]?.values[0]?.name || "综合能力评估"}
                    </td>
                    <td className={`p-4 font-mono text-sm text-${metric.colorClass}`}>{metric.avgScore}</td>
                    <td className="p-4 whitespace-nowrap">
                      <span className={`text-xs font-bold px-3 py-1 rounded-full border whitespace-nowrap ${status.class}`}>
                        {status.label}
                      </span>
                    </td>
                  </tr>
                 )
              })}
            </tbody>
          </table>
        </div>
      </div>
      <div className="h-8"></div>
    </div>
  );
}
