"use client";

import { useMemo, useState } from "react";
import { Download, ChevronDown, CheckCircle2 } from "lucide-react";
import { useAuth } from "@/components/AuthProvider";
import { useD4Metrics } from "@/hooks/useD4Metrics";
import { toD4UserId } from "@/lib/d4Metrics";
import { buildRuntimeMetrics, type RuntimeMetric, type RuntimeMetricValue } from "@/lib/metricRuntime";

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

  const d4Query = useMemo(() => {
    const userId = user?.role === "stu" ? toD4UserId(user.id) : undefined;
    return userId ? { userId } : {};
  }, [user]);

  const d4Metrics = useD4Metrics(d4Query);

  const displayData = useMemo(
    () => buildRuntimeMetrics({ data: d4Metrics.data, error: d4Metrics.error, isLoading: d4Metrics.isLoading }),
    [d4Metrics.data, d4Metrics.error, d4Metrics.isLoading],
  );

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

  const getScoreStatus = (score: number | null) => {
    if (score == null) {
      return { label: "暂无", class: "bg-surface-variant text-on-surface-variant border-outline-variant" };
    }

    if (score >= 90) return { label: "优秀", class: "bg-metric-high/10 text-metric-high border-metric-high/30" };
    if (score >= 80) return { label: "良好", class: "bg-metric-mid/10 text-metric-mid border-metric-mid/30" };
    if (score >= 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" };
  };

  const getMetricStatus = (metric: RuntimeMetric) => {
    if (metric.state === "loading") {
      return { label: "加载中", class: "bg-primary/10 text-primary border-primary/30" };
    }

    if (metric.state === "error") {
      return { label: "接口异常", class: "bg-metric-low/10 text-metric-low border-metric-low/30" };
    }

    if (metric.state === "unavailable") {
      return { label: "未接入", class: "bg-surface-variant text-on-surface-variant border-outline-variant" };
    }

    return getScoreStatus(metric.score);
  };

  const getValueStatus = (value: RuntimeMetricValue) => {
    if (value.state === "ready" && value.score == null) {
      return { label: "已同步", class: "bg-primary/10 text-primary border-primary/30" };
    }

    if (value.state === "loading") {
      return { label: "加载中", class: "bg-primary/10 text-primary border-primary/30" };
    }

    if (value.state === "error") {
      return { label: "异常", class: "bg-metric-low/10 text-metric-low border-metric-low/30" };
    }

    if (value.state === "unavailable") {
      return { label: "未接入", class: "bg-surface-variant text-on-surface-variant border-outline-variant" };
    }

    return getScoreStatus(value.score);
  };

  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">
        {displayData[activeTab].map((metric) => {
          const status = getMetricStatus(metric);
          const progress = metric.score ?? 0;

          return (
            <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 gap-4">
                <div className="flex items-center gap-4 min-w-0">
                  <div className={`h-14 w-14 rounded-2xl flex items-center justify-center shrink-0 ${metric.bgClass}`}>
                    <span className="font-bold text-xl">
                      {metric.id}
                    </span>
                  </div>
                  <div className="min-w-0">
                    <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.summary}
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-4 shrink-0">
                  <div className="text-right hidden sm:block">
                    <div className={`text-2xl font-bold ${metric.score == null ? "text-outline" : `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 transition-all duration-500"
                  style={{
                    width: `${progress}%`,
                    backgroundColor: metric.score == null ? "var(--color-outline-variant)" : `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) => {
                    const subStatus = subMetric.state === "ready" ? getScoreStatus(subMetric.score) : status;

                    return (
                      <div key={subMetric.id}>
                        <div className="flex justify-between items-center mb-3 gap-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 whitespace-nowrap ${subStatus.class}`}>
                            {subStatus.label}
                          </span>
                        </div>
                        <div className="grid gap-2">
                          {subMetric.values.map((val, idx) => {
                            const valueStatus = getValueStatus(val);

                            return (
                              <div key={idx} className="text-sm p-3 rounded-lg bg-surface-container-high border border-outline-variant/20 transition-colors">
                                <div className="flex items-center justify-between gap-3">
                                  <div className="flex items-center text-secondary min-w-0">
                                    <CheckCircle2 className={`w-4 h-4 mr-3 shrink-0 ${val.state === "ready" ? `text-${metric.colorClass}` : "text-outline"}`} />
                                    <span className="truncate">{val.name}</span>
                                  </div>
                                  <div className="flex items-center gap-3 shrink-0">
                                    <span className="font-mono text-on-surface">{val.displayValue}</span>
                                    <span className={`text-[10px] font-bold border px-2 py-0.5 rounded-full ${valueStatus.class}`}>
                                      {valueStatus.label}
                                    </span>
                                  </div>
                                </div>
                                {val.helperText && (
                                  <p className="text-xs text-outline mt-2 pl-7">
                                    {val.helperText}
                                  </p>
                                )}
                                {val.progress != null && (
                                  <div className="mt-3 ml-7 h-1.5 rounded-full bg-surface-variant overflow-hidden">
                                    <div
                                      className="h-full rounded-full"
                                      style={{
                                        width: `${val.progress}%`,
                                        backgroundColor: `var(--color-${metric.colorClass})`,
                                      }}
                                    ></div>
                                  </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">
              {displayData[activeTab].map((metric) => {
                const status = getMetricStatus(metric);

                return (
                  <tr
                    key={metric.id}
                    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.id === "D4" ? "后端 D4 指标接口" : "等待后端接口"}
                    </td>
                    <td className={`p-4 font-mono text-sm ${metric.score == null ? "text-outline" : `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>
  );
}
