"use client";

import { useState, useEffect, useMemo, useRef } from "react";
import { Badge } from "@/components/ui/badge";
import { Card } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { DepthMapPlotly } from "@/components/depth-map-plotly";
import OrderBookDepthMap from "@/components/orderbook-depth-map";
import { EquityChart } from "@/components/equity-chart";
import {
  type L2Snapshot, type SurfaceData, type ImbalanceMetrics,
  L2RingBuffer, l2SnapshotsToSurface, computeImbalance, generateSyntheticSnapshots,
} from "@/lib/depth-map-utils";
import type { Strategy, Trade, LiveMetrics } from "@/lib/types";
import { Activity } from "lucide-react";

interface OBIDetailProps {
  strategy: Strategy;
  strategyName: string;
  equityData: { t: number; v: number }[];
  trades: Trade[];
  liveData: LiveMetrics | null;
  color: string;
}

export function OBIDetail({ strategy, strategyName, equityData, trades, liveData, color }: OBIDetailProps) {
  const ringBuffer = useRef(new L2RingBuffer(60));
  const [, setTick] = useState(0);

  // Generate synthetic L2 data for live visualization
  useEffect(() => {
    // Initial batch
    const snaps = generateSyntheticSnapshots(60);
    for (const s of snaps) ringBuffer.current.push(s);
    setTick(t => t + 1);

    // Continuous updates
    const iv = setInterval(() => {
      const newSnaps = generateSyntheticSnapshots(1);
      ringBuffer.current.push(newSnaps[0]);
      setTick(t => t + 1);
    }, 2000);

    return () => clearInterval(iv);
  }, []);

  // Compute dual surface + metrics
  const snapsNow = ringBuffer.current.snapshot();
  const surfaceNow: SurfaceData | null = snapsNow.length >= 3
    ? l2SnapshotsToSurface(snapsNow, 50, 60)
    : null;
  const metricsNow: ImbalanceMetrics | null = snapsNow.length > 0
    ? computeImbalance(snapsNow[snapsNow.length - 1])
    : null;

  // Strategy stats
  const pnl = strategy.pnl ?? 0;
  const pnlPct = strategy.pnl_pct ?? 0;
  const winRate = strategy.win_rate ?? 0;

  // BTC buy-and-hold from live data
  const btcPrice = liveData?.equity_history?.length
    ? liveData.equity_history[liveData.equity_history.length - 1].v
    : null;
  const btcStart = liveData?.equity_history?.length
    ? liveData.equity_history[0].v
    : null;
  const btcReturn = btcPrice && btcStart ? ((btcPrice - btcStart) / btcStart * 100) : null;

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-xs font-bold flex items-center gap-2">
            <Activity className="w-4 h-4 text-amber-400" />
            Order Book Imbalance • BTC-USD-PERP
          </h3>
          <p className="text-[10px] text-muted-foreground mt-1">
            L2 bid/ask volume skew — 3D depth map with synchronized bid/ask subplots
          </p>
        </div>
      </div>

      {/* 3D Subplots: Bid (left) + Ask (right) */}
      <Card className="overflow-hidden border-border">
        <DepthMapPlotly surface={surfaceNow} metrics={metricsNow} height={440} />
      </Card>

      {/* Metrics Row */}
      <div className="grid grid-cols-3 sm:grid-cols-6 gap-2">
        {([
          { l: "Strategy PnL", v: `$${pnl.toFixed(4)} (${pnlPct >= 0 ? "+" : ""}${pnlPct.toFixed(2)}%)`, up: pnlPct >= 0 },
          { l: "BTC B&H", v: btcReturn !== null ? `${btcReturn >= 0 ? "+" : ""}${btcReturn.toFixed(2)}%` : "—", up: (btcReturn ?? 0) >= 0 },
          { l: "Hit Rate", v: `${Math.round(winRate * 100)}%` },
          { l: "Imbalance", v: metricsNow ? `${metricsNow.imbalance > 0 ? "+" : ""}${metricsNow.imbalance.toFixed(3)}` : "—", up: (metricsNow?.imbalance ?? 0) > 0 },
          { l: "Bid Vol", v: metricsNow ? `$${metricsNow.bidVolume.toFixed(1)}` : "—" },
          { l: "Ask Vol", v: metricsNow ? `$${metricsNow.askVolume.toFixed(1)}` : "—" },
        ]).map(({ l, v, up }) => (
          <div key={l} className="p-3 rounded-lg border border-border bg-card/50">
            <p className="text-[9px] text-muted-foreground uppercase tracking-wider mb-1">{l}</p>
            <p className={`text-sm font-mono font-semibold ${up === true ? "text-green-500" : up === false ? "text-red-500" : ""}`}>
              {v}
            </p>
          </div>
        ))}
      </div>

      {/* Equity Curve: Strategy vs BTC B&H */}
      {equityData.length > 0 && (
        <div>
          <p className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-2">
            Equity Curve — {strategyName} vs BTC Buy & Hold
          </p>
          <div className="rounded-lg border border-border overflow-hidden h-[260px]">
            <EquityChart data={equityData} color={color} height={260} />
          </div>
        </div>
      )}

      {/* Trade History */}
      <div>
        <h4 className="text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-2 pb-2 border-b border-border">
          Trade History {trades.length > 0 ? `(${trades.length})` : ""}
        </h4>
        {trades.length > 0 ? (
          <div className="overflow-x-auto rounded-lg border border-border">
            <Table>
              <TableHeader>
                <TableRow className="border-border hover:bg-transparent">
                  <TableHead className="text-[9px] h-7">Time</TableHead>
                  <TableHead className="text-[9px] h-7">Side</TableHead>
                  <TableHead className="text-[9px] h-7">Size</TableHead>
                  <TableHead className="text-[9px] h-7">Price</TableHead>
                  <TableHead className="text-[9px] h-7 text-right">PnL</TableHead>
                  <TableHead className="text-[9px] h-7 text-right">Fee</TableHead>
                  <TableHead className="text-[9px] h-7">Reason</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {trades.slice(-100).reverse().map((t, i) => (
                  <TableRow key={i} className="border-border/50 hover:bg-muted/30">
                    <TableCell className="text-[10px] py-1.5 font-mono whitespace-nowrap">{(t.time ?? "").substring(0, 16)}</TableCell>
                    <TableCell className="text-[10px] py-1.5">
                      <Badge variant="outline" className={`text-[9px] h-4 px-1.5 border-0 ${(t.side ?? "").indexOf("BUY") >= 0 ? "bg-green-500/10 text-green-500" : "bg-red-500/10 text-red-500"}`}>
                        {t.side ?? "—"}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-[10px] py-1.5 font-mono">{t.size}</TableCell>
                    <TableCell className="text-[10px] py-1.5 font-mono">${(t.price ?? 0).toFixed(1)}</TableCell>
                    <TableCell className={`text-[10px] py-1.5 font-mono text-right ${(t.pnl ?? 0) >= 0 ? "text-green-500" : "text-red-500"}`}>
                      {(t.pnl ?? 0) >= 0 ? "+" : ""}${Math.abs(t.pnl ?? 0).toFixed(4)}
                    </TableCell>
                    <TableCell className="text-[10px] py-1.5 font-mono text-right text-red-400">${(t.fee ?? 0).toFixed(4)}</TableCell>
                    <TableCell className="text-[10px] py-1.5 text-muted-foreground max-w-[200px] truncate">{t.reason ?? "—"}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
        ) : (
          <p className="text-xs text-muted-foreground text-center py-8">No trades recorded yet</p>
        )}
      </div>
      {/* Live L2 Order Book + Trade Tape */}
      <div className="mt-6">
        <OrderBookDepthMap coin="BTC" height={480} topRatio={0.55} />
      </div>
    </div>
  );
}
