import { createFileRoute } from "@tanstack/react-router";
import { useState, useEffect, useMemo } from "react";
import { fetchSectors, type SectorItem, type SectorType } from "@/lib/stock-api";
import { Card, CardContent } from "@/components/ui/card";
import { ArrowLeft, TrendingUp, TrendingDown, RefreshCw } from "lucide-react";
import { Link } from "@tanstack/react-router";

export const Route = createFileRoute("/sectors")({
  component: SectorsPage,
});

const TABS: { key: SectorType; label: string }[] = [
  { key: "industry", label: "行业板块" },
  { key: "concept", label: "概念板块" },
];

type SortMode = "mainNetInflow" | "changePercent";

function SectorsPage() {
  const [tab, setTab] = useState<SectorType>("industry");
  const [data, setData] = useState<SectorItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [sort, setSort] = useState<SortMode>("mainNetInflow");

  const loadData = (t: SectorType) => {
    setLoading(true);
    fetchSectors(t).then((items) => {
      setData(items);
      setLoading(false);
    });
  };

  useEffect(() => {
    loadData(tab);
  }, [tab]);

  const sorted = useMemo(() => {
    return [...data].sort((a, b) => {
      if (sort === "mainNetInflow") return b.mainNetInflow - a.mainNetInflow;
      return (b.changePercent ?? 0) - (a.changePercent ?? 0);
    });
  }, [data, sort]);

  return (
    <div className="min-h-screen bg-background">
      {/* 顶栏 */}
      <header className="sticky top-0 z-10 bg-background/95 backdrop-blur border-b">
        <div className="max-w-5xl mx-auto px-4 h-12 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Link to="/" className="hover:opacity-70 transition-opacity">
              <ArrowLeft className="h-5 w-5" />
            </Link>
            <h1 className="text-base font-semibold">板块资金流向</h1>
          </div>
          <button
            onClick={() => loadData(tab)}
            className="text-muted-foreground hover:text-foreground transition-colors"
          >
            <RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
          </button>
        </div>
      </header>

      {/* Tab + Sorting 切换 */}
      <div className="max-w-5xl mx-auto px-4 mt-4 flex items-center gap-2">
        <div className="flex gap-1 bg-muted rounded-lg p-1 flex-1">
          {TABS.map((t) => (
            <button
              key={t.key}
              onClick={() => setTab(t.key)}
              className={`flex-1 py-1.5 text-sm font-medium rounded-md transition-colors ${
                tab === t.key
                  ? "bg-background text-foreground shadow-sm"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              {t.label}
            </button>
          ))}
        </div>
        <div className="flex gap-0.5 text-xs border rounded overflow-hidden shrink-0">
          <button onClick={() => setSort("mainNetInflow")}
            className={`px-2 py-1 transition-colors ${
              sort === "mainNetInflow"
                ? "bg-primary text-primary-foreground"
                : "text-muted-foreground hover:text-foreground"
            }`}
          >主力</button>
          <button onClick={() => setSort("changePercent")}
            className={`px-2 py-1 transition-colors ${
              sort === "changePercent"
                ? "bg-primary text-primary-foreground"
                : "text-muted-foreground hover:text-foreground"
            }`}
          >涨幅</button>
        </div>
      </div>

      {/* 数据信息 */}
      <div className="max-w-5xl mx-auto px-4 mt-2">
        <p className="text-[10px] text-muted-foreground">
          含 {sorted.length} 个板块 · 按{sort === "mainNetInflow" ? "主力净流入" : "涨跌幅"}降序
        </p>
      </div>

      {/* 卡片网格 */}
      <div className="max-w-5xl mx-auto px-4 mt-3 pb-8">
        {loading ? (
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
            {Array.from({ length: 20 }).map((_, i) => (
              <div key={i} className="animate-pulse rounded-xl bg-muted h-32" />
            ))}
          </div>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
            {sorted.map((item) => (
              <SectorBlock key={item.code} item={item} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function formatInflow(val: number | null | undefined): string {
  if (val == null) return "--";
  const abs = Math.abs(val);
  if (abs >= 1e8) return (val / 1e8).toFixed(2) + "亿";
  if (abs >= 1e4) return (val / 1e4).toFixed(0) + "万";
  return val.toFixed(0);
}

function FundFlowBar({ value, maxAbs }: { value: number | null | undefined; maxAbs: number }) {
  if (value == null) return null;
  const pct = maxAbs > 0 ? (value / maxAbs) * 100 : 0;
  const isPos = value >= 0;
  return (
    <div className="flex items-center gap-1">
      <div className="flex-1 h-1.5 rounded-full bg-muted overflow-hidden">
        <div
          className={`h-full rounded-full transition-all ${
            isPos ? "bg-red-500/60" : "bg-green-500/60"
          }`}
          style={{ width: `${Math.min(Math.abs(pct), 100)}%`, marginLeft: isPos ? "50%" : undefined }}
        />
      </div>
      <span className={`text-[10px] font-medium tabular-nums w-14 text-right ${
        isPos ? "text-red-500" : "text-green-500"
      }`}>
        {formatInflow(value)}
      </span>
    </div>
  );
}

function SectorBlock({ item }: { item: SectorItem }) {
  const inflow = item.mainNetInflow;
  const isPositive = inflow >= 0;
  const change = item.changePercent;
  const maxAbs = Math.max(
    Math.abs(item.mainNetInflow),
    Math.abs(item.superLargeInflow ?? 0),
    Math.abs(item.largeInflow ?? 0),
    Math.abs(item.mediumInflow ?? 0),
    Math.abs(item.smallInflow ?? 0),
    1
  );

  return (
    <Card className="rounded-xl hover:shadow-md transition-shadow">
      <CardContent className="p-3 space-y-2">
        {/* 板块名称 */}
        <div className="flex items-center justify-between gap-1">
          <p className="text-sm font-medium truncate" title={item.name}>
            {item.name}
          </p>
          {item.code && (
            <span className="shrink-0 text-[9px] text-muted-foreground/60 font-mono">
              {item.code.replace("BK", "")}
            </span>
          )}
        </div>

        {/* 涨跌幅 */}
        <div className="flex items-center justify-between">
          {change != null ? (
            <span
              className={`inline-flex items-center gap-0.5 text-xs font-semibold ${
                change >= 0 ? "text-red-500" : "text-green-500"
              }`}
            >
              {change >= 0 ? (
                <TrendingUp className="h-3 w-3" />
              ) : (
                <TrendingDown className="h-3 w-3" />
              )}
              {change >= 0 ? "+" : ""}
              {change.toFixed(2)}%
            </span>
          ) : (
            <span className="text-xs text-muted-foreground">--</span>
          )}
          <span className="text-[10px] text-muted-foreground">
            {formatInflow(item.turnover)}
          </span>
        </div>

        {/* 主力净流入 */}
        <div className="pt-1.5 border-t border-border/40">
          <div className="flex items-center justify-between mb-1">
            <span className="text-[10px] text-muted-foreground">主力净流入</span>
            <span className={`text-xs font-bold tabular-nums ${
              isPositive ? "text-red-500" : "text-green-500"
            }`}>
              {isPositive ? "+" : ""}{formatInflow(inflow)}
            </span>
          </div>

          {/* 资金流向明细条 */}
          <div className="space-y-0.5">
            <FundFlowBar value={item.superLargeInflow} maxAbs={maxAbs} />
            <FundFlowBar value={item.largeInflow} maxAbs={maxAbs} />
            <FundFlowBar value={item.mediumInflow} maxAbs={maxAbs} />
            <FundFlowBar value={item.smallInflow} maxAbs={maxAbs} />
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
