"use client";
import { useState, useEffect } from "react";
import Link from "next/link";
import { authFetch } from "@/lib/auth";
import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, ReferenceLine, Area, AreaChart } from "recharts";

// ─── 工具函数 ────────────────────────────────────────────────────

function bjt(ms: number) {
  const d = new Date(ms + 8 * 3600 * 1000);
  return `${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(d.getUTCDate()).padStart(2, "0")} ${String(d.getUTCHours()).padStart(2, "0")}:${String(d.getUTCMinutes()).padStart(2, "0")}`;
}

function fmtPrice(p: number) {
  return p < 100 ? p.toFixed(4) : p.toLocaleString("en-US", { minimumFractionDigits: 1, maximumFractionDigits: 1 });
}

// ─── 总览面板 ────────────────────────────────────────────────────

function SummaryCards() {
  const [data, setData] = useState<any>(null);
  useEffect(() => {
    const f = async () => { try { const r = await authFetch("/api/paper/summary"); if (r.ok) setData(await r.json()); } catch {} };
    f(); const iv = setInterval(f, 10000); return () => clearInterval(iv);
  }, []);
  if (!data) return <div className="text-center text-slate-400 text-sm py-4">加载中...</div>;
  return (
    <div className="grid grid-cols-3 lg:grid-cols-6 gap-1.5">
      <div className="bg-white rounded-lg border border-slate-200 px-2.5 py-2">
        <p className="text-[10px] text-slate-400">总盈亏(R)</p>
        <p className={`font-mono font-bold text-lg ${data.total_pnl >= 0 ? "text-emerald-600" : "text-red-500"}`}>{data.total_pnl >= 0 ? "+" : ""}{data.total_pnl}</p>
      </div>
      <div className="bg-white rounded-lg border border-slate-200 px-2.5 py-2">
        <p className="text-[10px] text-slate-400">胜率</p>
        <p className="font-mono font-bold text-lg text-slate-800">{data.win_rate}%</p>
      </div>
      <div className="bg-white rounded-lg border border-slate-200 px-2.5 py-2">
        <p className="text-[10px] text-slate-400">总交易</p>
        <p className="font-mono font-bold text-lg text-slate-800">{data.total_trades}</p>
      </div>
      <div className="bg-white rounded-lg border border-slate-200 px-2.5 py-2">
        <p className="text-[10px] text-slate-400">持仓中</p>
        <p className="font-mono font-bold text-lg text-blue-600">{data.active_positions}</p>
      </div>
      <div className="bg-white rounded-lg border border-slate-200 px-2.5 py-2">
        <p className="text-[10px] text-slate-400">盈亏比(PF)</p>
        <p className="font-mono font-bold text-lg text-slate-800">{data.profit_factor}</p>
      </div>
      <div className="bg-white rounded-lg border border-slate-200 px-2.5 py-2">
        <p className="text-[10px] text-slate-400">运行</p>
        <p className="font-mono font-semibold text-sm text-slate-600">{data.start_time ? "运行中 ✅" : "等待首笔"}</p>
      </div>
    </div>
  );
}

// ─── 当前持仓 ────────────────────────────────────────────────────

function ActivePositions() {
  const [positions, setPositions] = useState<any[]>([]);
  useEffect(() => {
    const f = async () => { try { const r = await authFetch("/api/paper/positions"); if (r.ok) { const j = await r.json(); setPositions(j.data || []); } } catch {} };
    f(); const iv = setInterval(f, 5000); return () => clearInterval(iv);
  }, []);

  if (positions.length === 0) return (
    <div className="rounded-xl border border-slate-200 bg-white px-3 py-4 text-center text-slate-400 text-sm">
      暂无活跃持仓
    </div>
  );

  return (
    <div className="rounded-xl border border-slate-200 bg-white overflow-hidden">
      <div className="px-3 py-2 border-b border-slate-100">
        <h3 className="font-semibold text-slate-800 text-xs">当前持仓</h3>
      </div>
      <div className="divide-y divide-slate-100">
        {positions.map((p: any) => {
          const sym = p.symbol?.replace("USDT", "") || "";
          const holdMin = Math.round((Date.now() - p.entry_ts) / 60000);
          return (
            <div key={p.id} className="px-3 py-2">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <span className={`text-xs font-bold ${p.direction === "LONG" ? "text-emerald-600" : "text-red-500"}`}>
                    {p.direction === "LONG" ? "🟢" : "🔴"} {sym} {p.direction}
                  </span>
                  <span className="text-[10px] text-slate-400">评分{p.score} · {p.tier === "heavy" ? "加仓" : p.tier === "standard" ? "标准" : "轻仓"}</span>
                </div>
                <span className="text-[10px] text-slate-400">{holdMin}分钟</span>
              </div>
              <div className="flex gap-3 mt-1 text-[10px] font-mono text-slate-600">
                <span>入场: ${fmtPrice(p.entry_price)}</span>
                <span className="text-emerald-600">TP1: ${fmtPrice(p.tp1_price)}{p.tp1_hit ? " ✅" : ""}</span>
                <span className="text-emerald-600">TP2: ${fmtPrice(p.tp2_price)}</span>
                <span className="text-red-500">SL: ${fmtPrice(p.sl_price)}</span>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── 权益曲线 ────────────────────────────────────────────────────

function EquityCurve() {
  const [data, setData] = useState<any[]>([]);
  useEffect(() => {
    const f = async () => { try { const r = await authFetch("/api/paper/equity-curve"); if (r.ok) { const j = await r.json(); setData(j.data || []); } } catch {} };
    f(); const iv = setInterval(f, 30000); return () => clearInterval(iv);
  }, []);

  if (data.length < 2) return null;

  return (
    <div className="rounded-xl border border-slate-200 bg-white overflow-hidden">
      <div className="px-3 py-2 border-b border-slate-100">
        <h3 className="font-semibold text-slate-800 text-xs">权益曲线 (累计PnL)</h3>
      </div>
      <div className="p-2" style={{ height: 200 }}>
        <ResponsiveContainer width="100%" height="100%">
          <AreaChart data={data}>
            <XAxis dataKey="ts" tickFormatter={(v) => bjt(v)} tick={{ fontSize: 10 }} />
            <YAxis tick={{ fontSize: 10 }} tickFormatter={(v) => `${v}R`} />
            <Tooltip labelFormatter={(v) => bjt(Number(v))} formatter={(v: any) => [`${v}R`, "累计PnL"]} />
            <ReferenceLine y={0} stroke="#94a3b8" strokeDasharray="3 3" />
            <Area type="monotone" dataKey="pnl" stroke="#10b981" fill="#d1fae5" strokeWidth={2} />
          </AreaChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}

// ─── 历史交易列表 ────────────────────────────────────────────────

type FilterSymbol = "all" | "BTC" | "ETH" | "XRP" | "SOL";
type FilterResult = "all" | "win" | "loss";

function TradeHistory() {
  const [trades, setTrades] = useState<any[]>([]);
  const [symbol, setSymbol] = useState<FilterSymbol>("all");
  const [result, setResult] = useState<FilterResult>("all");

  useEffect(() => {
    const f = async () => {
      try {
        const r = await authFetch(`/api/paper/trades?symbol=${symbol}&result=${result}&limit=50`);
        if (r.ok) { const j = await r.json(); setTrades(j.data || []); }
      } catch {}
    };
    f(); const iv = setInterval(f, 10000); return () => clearInterval(iv);
  }, [symbol, result]);

  return (
    <div className="rounded-xl border border-slate-200 bg-white overflow-hidden">
      <div className="px-3 py-2 border-b border-slate-100 flex items-center justify-between flex-wrap gap-1">
        <h3 className="font-semibold text-slate-800 text-xs">历史交易</h3>
        <div className="flex gap-1">
          {(["all", "BTC", "ETH", "XRP", "SOL"] as FilterSymbol[]).map(s => (
            <button key={s} onClick={() => setSymbol(s)}
              className={`px-2 py-0.5 rounded text-[10px] ${symbol === s ? "bg-slate-800 text-white" : "text-slate-500 hover:bg-slate-100"}`}>
              {s === "all" ? "全部" : s}
            </button>
          ))}
          <span className="text-slate-300">|</span>
          {(["all", "win", "loss"] as FilterResult[]).map(r => (
            <button key={r} onClick={() => setResult(r)}
              className={`px-2 py-0.5 rounded text-[10px] ${result === r ? "bg-slate-800 text-white" : "text-slate-500 hover:bg-slate-100"}`}>
              {r === "all" ? "全部" : r === "win" ? "盈利" : "亏损"}
            </button>
          ))}
        </div>
      </div>
      <div className="max-h-64 overflow-y-auto">
        {trades.length === 0 ? (
          <div className="text-center text-slate-400 text-sm py-6">暂无交易记录</div>
        ) : (
          <table className="w-full text-[11px]">
            <thead className="bg-slate-50 sticky top-0">
              <tr className="text-slate-500">
                <th className="px-2 py-1.5 text-left font-medium">币种</th>
                <th className="px-2 py-1.5 text-left font-medium">方向</th>
                <th className="px-2 py-1.5 text-right font-medium">入场</th>
                <th className="px-2 py-1.5 text-right font-medium">出场</th>
                <th className="px-2 py-1.5 text-right font-medium">PnL(R)</th>
                <th className="px-2 py-1.5 text-center font-medium">状态</th>
                <th className="px-2 py-1.5 text-right font-medium">分数</th>
                <th className="px-2 py-1.5 text-right font-medium">时间</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50">
              {trades.map((t: any) => {
                const holdMin = t.exit_ts && t.entry_ts ? Math.round((t.exit_ts - t.entry_ts) / 60000) : 0;
                return (
                  <tr key={t.id} className="hover:bg-slate-50">
                    <td className="px-2 py-1.5 font-mono">{t.symbol?.replace("USDT", "")}</td>
                    <td className={`px-2 py-1.5 font-bold ${t.direction === "LONG" ? "text-emerald-600" : "text-red-500"}`}>
                      {t.direction === "LONG" ? "🟢" : "🔴"} {t.direction}
                    </td>
                    <td className="px-2 py-1.5 text-right font-mono">{fmtPrice(t.entry_price)}</td>
                    <td className="px-2 py-1.5 text-right font-mono">{t.exit_price ? fmtPrice(t.exit_price) : "-"}</td>
                    <td className={`px-2 py-1.5 text-right font-mono font-bold ${t.pnl_r > 0 ? "text-emerald-600" : t.pnl_r < 0 ? "text-red-500" : "text-slate-500"}`}>
                      {t.pnl_r > 0 ? "+" : ""}{t.pnl_r?.toFixed(2)}
                    </td>
                    <td className="px-2 py-1.5 text-center">
                      <span className={`px-1 py-0.5 rounded text-[9px] ${
                        t.status === "tp" ? "bg-emerald-100 text-emerald-700" :
                        t.status === "sl" ? "bg-red-100 text-red-700" :
                        t.status === "sl_be" ? "bg-amber-100 text-amber-700" :
                        "bg-slate-100 text-slate-600"
                      }`}>
                        {t.status === "tp" ? "止盈" : t.status === "sl" ? "止损" : t.status === "sl_be" ? "保本" : t.status === "timeout" ? "超时" : t.status}
                      </span>
                    </td>
                    <td className="px-2 py-1.5 text-right font-mono">{t.score}</td>
                    <td className="px-2 py-1.5 text-right text-slate-400">{holdMin}m</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

// ─── 统计面板 ────────────────────────────────────────────────────

function StatsPanel() {
  const [data, setData] = useState<any>(null);
  useEffect(() => {
    const f = async () => { try { const r = await authFetch("/api/paper/stats"); if (r.ok) setData(await r.json()); } catch {} };
    f(); const iv = setInterval(f, 30000); return () => clearInterval(iv);
  }, []);

  if (!data || data.error) return null;

  return (
    <div className="rounded-xl border border-slate-200 bg-white overflow-hidden">
      <div className="px-3 py-2 border-b border-slate-100">
        <h3 className="font-semibold text-slate-800 text-xs">详细统计</h3>
      </div>
      <div className="p-3 grid grid-cols-2 lg:grid-cols-4 gap-2 text-xs">
        <div><span className="text-slate-400">胜率</span><p className="font-mono font-bold">{data.win_rate}%</p></div>
        <div><span className="text-slate-400">盈亏比</span><p className="font-mono font-bold">{data.win_loss_ratio}</p></div>
        <div><span className="text-slate-400">平均盈利</span><p className="font-mono font-bold text-emerald-600">+{data.avg_win}R</p></div>
        <div><span className="text-slate-400">平均亏损</span><p className="font-mono font-bold text-red-500">-{data.avg_loss}R</p></div>
        <div><span className="text-slate-400">最大回撤</span><p className="font-mono font-bold">{data.mdd}R</p></div>
        <div><span className="text-slate-400">夏普比率</span><p className="font-mono font-bold">{data.sharpe}</p></div>
        <div><span className="text-slate-400">做多胜率</span><p className="font-mono">{data.long_win_rate}% ({data.long_count}笔)</p></div>
        <div><span className="text-slate-400">做空胜率</span><p className="font-mono">{data.short_win_rate}% ({data.short_count}笔)</p></div>
        {data.by_symbol && Object.entries(data.by_symbol).map(([s, v]: [string, any]) => (
          <div key={s}><span className="text-slate-400">{s}胜率</span><p className="font-mono">{v.win_rate}% ({v.total}笔)</p></div>
        ))}
        {data.by_tier && Object.entries(data.by_tier).map(([t, v]: [string, any]) => (
          <div key={t}><span className="text-slate-400">{t === "heavy" ? "加仓" : t === "standard" ? "标准" : "轻仓"}档</span><p className="font-mono">{v.win_rate}% ({v.total}笔)</p></div>
        ))}
      </div>
    </div>
  );
}

// ─── 主页面 ──────────────────────────────────────────────────────

export default function PaperTradingPage() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  useEffect(() => {
    const token = typeof window !== "undefined" ? localStorage.getItem("token") : null;
    setIsLoggedIn(!!token);
  }, []);

  if (!isLoggedIn) return (
    <div className="flex flex-col items-center justify-center h-64 gap-4">
      <div className="text-5xl">🔒</div>
      <p className="text-slate-600 font-medium">请先登录查看模拟盘</p>
      <Link href="/login" className="bg-blue-600 text-white px-4 py-2 rounded-lg text-sm">登录</Link>
    </div>
  );

  return (
    <div className="space-y-3">
      <div>
        <h1 className="text-lg font-bold text-slate-900">📊 模拟盘</h1>
        <p className="text-[10px] text-slate-500">V5.1信号引擎自动交易 · 实时追踪 · 数据驱动优化</p>
      </div>

      <SummaryCards />
      <ActivePositions />
      <EquityCurve />
      <TradeHistory />
      <StatsPanel />
    </div>
  );
}
