"use client";

import Link from "next/link";
import { useLiveSimulation } from "@/components/useLiveSimulation";
import type { CnIndependentPositionRow } from "@/lib/live-simulation";

const money = (value: number) => `¥${value.toLocaleString("zh-CN", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
const percent = (value: number) => `${value >= 0 ? "+" : ""}${(value * 100).toFixed(2)}%`;
const stamp = (value: string | undefined) => value
  ? new Date(value).toLocaleString("zh-CN", { hour12: false, timeZone: "Asia/Shanghai" })
  : "—";

export function HoldingsExplorer({ symbol }: { symbol?: string }) {
  const { data, connected, error } = useLiveSimulation();
  const mirror = data.cnLiveMirror;
  const accounts = data.cnIndependentAccounts;
  const independentRows = accounts ? [
    ...(accounts.aShareT1.positionRows ?? []),
    ...(accounts.intradayEtfT0.positionRows ?? []),
    ...(accounts.convertibleBondT0.positionRows ?? []),
  ] : [];
  const fallbackEtfRows: CnIndependentPositionRow[] = mirror?.positions
    .filter((position) => position.qty !== 0)
    .map((position) => ({
      accountId: "CN-ETF-T0-SHADOW",
      sleeve: "ETF_T0",
      symbol: position.symbol,
      name: position.name,
      qty: position.qty,
      avgCost: position.avg_cost,
      latestPrice: position.price,
      marketValue: position.market_value,
      unrealizedPnl: position.unrealized_pnl,
      positionReturn: position.avg_cost ? position.price / position.avg_cost - 1 : 0,
      updatedAt: position.updated_at,
      strategyLogic: "趋势、VWAP、流动性、波动率与多角色研究闸门共同通过",
      expectedHolding: "日内动态持有；风险条件可提前退出，最迟14:55尝试清仓",
      sellReference: "依据最新价、移动止损、盘口容量与风险阈值动态计算",
      exitLogic: "趋势或VWAP转弱、移动止损、组合熔断、流动性恶化或14:55清仓",
      tradeRule: "场内基金T+0；限价、排队、部分成交及撤单竞态均计入",
    })) ?? [];
  const positions = independentRows.length ? independentRows : fallbackEtfRows;
  const selected = symbol ? positions.find((position) => position.symbol === symbol) : undefined;
  const selectedTrades = symbol ? (mirror?.trades.filter((trade) => trade.symbol === symbol) ?? []) : [];
  const sleeveLabel = selected?.sleeve === "A_SHARE_T1" ? "A股个股 · T+1" : selected?.sleeve === "CONVERTIBLE_BOND_T0" ? "可转债 · T+0" : "场内ETF · T+0";

  if (symbol) return <div className="holdings-page">
    <section className="holding-detail-hero">
      <div><span>POSITION DETAIL / SHADOW ONLY</span><h1>{symbol} · {selected?.name ?? "当前未持有"}</h1><p>以下为影子账户持仓与确定性策略规则，不是收益承诺，也不是券商成交回报。</p></div>
      <Link href="/positions">← 返回全部持仓</Link>
    </section>
    {selected ? <>
      <section className="holding-detail-kpis">
        <article><span>持仓数量</span><b>{selected.qty.toLocaleString("zh-CN")} 份</b><small>{sleeveLabel}</small></article>
        <article><span>平均买入成本</span><b>{money(selected.avgCost)}</b><small>模拟费用计入成交账本</small></article>
        <article><span>最新研究价</span><b>{money(selected.latestPrice)}</b><small>更新时间 {stamp(selected.updatedAt)}</small></article>
        <article><span>持仓收益率</span><b className={selected.positionReturn < 0 ? "negative" : "positive"}>{percent(selected.positionReturn)}</b><small>未实现盈亏 {money(selected.unrealizedPnl)}</small></article>
      </section>
      <section className="holding-detail-grid">
        <article><span>为什么选择</span><h2>策略逻辑</h2><p>{selected.strategyLogic}</p></article>
        <article><span>预计持有时长</span><h2>{selected.expectedHolding}</h2><p>{selected.tradeRule}</p></article>
        <article><span>预计卖出信息</span><h2>动态条件参考</h2><p>{selected.sellReference}。这不是目标价或必成交价，最终限价还要依据当时盘口、排队、冲击成本与撤单竞态计算。</p></article>
        <article><span>卖出触发</span><h2>风险优先于收益目标</h2><p>{selected.exitLogic}。若容量不足，系统会记录部分成交、等待、撤单或超时，不虚构完全成交。</p></article>
      </section>
      <section className="holding-trade-history"><header><span>POSITION EXECUTIONS</span><h2>该标的影子成交</h2></header>{selectedTrades.length ? selectedTrades.slice().reverse().map((trade) => <div key={trade.id}><b>{trade.side}</b><span>{trade.qty} × {money(trade.price)}</span><span>费用 {money(trade.fee)}</span><em>{stamp(trade.ts)}</em></div>) : <p>当前接口未保留可展示的该标的成交事件。</p>}</section>
    </> : <section className="holding-not-found"><h2>当前没有这个标的的持仓</h2><p>只有真实存在于三个影子账本的持仓才展示买入价、持有逻辑和收益；系统不会为了填满页面而生成虚假持仓。</p><Link className="button primary" href="/positions">查看全部持仓</Link></section>}
  </div>;

  return <div className="holdings-page">
    <section className="holding-detail-hero"><div><span>ALL SHADOW POSITIONS</span><h1>全部当前持仓</h1><p>三个账户独立核算；A股、ETF、可转债不共享现金、持仓或熔断。</p></div><Link href="/">返回运行总览 →</Link></section>
    <section className="holding-account-strip">
      <article><span>A股 T+1</span><b>{accounts?.aShareT1.positions ?? 0} 个持仓</b><small>{money(accounts?.aShareT1.equity ?? 1_000_000)} · 动态短线</small></article>
      <article><span>ETF T+0</span><b>{accounts?.intradayEtfT0.positions ?? positions.length} 个持仓</b><small>{money(accounts?.intradayEtfT0.equity ?? 1_000_000)} · 日内清仓</small></article>
      <article><span>可转债 T+0</span><b>{accounts?.convertibleBondT0.positions ?? 0} 个持仓</b><small>{money(accounts?.convertibleBondT0.equity ?? 1_000_000)} · 数据闸门</small></article>
    </section>
    <section className="holdings-table-card"><header><div><span>POSITIONS</span><h2>持仓明细</h2></div><small className={connected ? "positive" : "hold"}>{connected ? "云端同步" : "正在重连"}</small></header>
      {error && <p className="universe-error">连接提示：{error}</p>}
      {positions.length ? <div className="responsive-table"><table><thead><tr><th>标的</th><th>数量</th><th>平均成本</th><th>最新价</th><th>市值</th><th>持仓收益</th><th>策略约束</th></tr></thead><tbody>{positions.map((position) => {
        return <tr key={`${position.accountId}-${position.symbol}`}><td><Link href={`/positions/${position.symbol}`}><b>{position.symbol}</b><small>{position.name} · 查看详情 →</small></Link></td><td>{position.qty}</td><td>{money(position.avgCost)}</td><td>{money(position.latestPrice)}</td><td>{money(position.marketValue)}</td><td className={position.positionReturn < 0 ? "negative" : "positive"}>{percent(position.positionReturn)}<small>{money(position.unrealizedPnl)}</small></td><td>{position.tradeRule}</td></tr>;
      })}</tbody></table></div> : <div className="holding-not-found"><h2>三个影子账户当前均为空仓</h2><p>空仓是当前策略结论，不代表引擎掉线。出现持仓后，这里会显示所有标的并可继续点击查看策略与盈亏详情。</p></div>}
    </section>
    <p className="risk-note">真实订单始终为0。预计卖出信息是条件与风险参考，不保证价格或成交。</p>
  </div>;
}
