"use client";

import { useEffect, useRef, useState, useMemo } from "react";
import { useHyperliquidWebSocket, type L2Snapshot, type TradeTapeEntry } from "@/lib/hyperliquid-ws";

// ═══════════ Colors ═══════════
const BID_C = "#00C853";
const ASK_C = "#FF1744";
const MID_C = "#FFEB3B";
const TRADE_C = "#FFAB00";
const TXT = "#CCCCCC";
const TXT_B = "#FFFFFF";
const BG = "#000000";
const PANEL_BG = "#0A0A10";
const GRID = "rgba(255,255,255,0.03)";

interface Props {
  coin?: string;
  className?: string;
}

export default function L2Terminal({ coin = "BTC", className = "" }: Props) {
  const { l2, trades, connected, error } = useHyperliquidWebSocket(coin);
  const domCanvas = useRef<HTMLCanvasElement>(null);
  const depthCanvas = useRef<HTMLCanvasElement>(null);
  const tapeCanvas = useRef<HTMLCanvasElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const [dims, setDims] = useState({ w: 1200, h: 800 });

  useEffect(() => {
    const cb = () => {
      if (containerRef.current) {
        setDims({ w: containerRef.current.clientWidth, h: window.innerHeight - 64 });
      }
    };
    cb();
    window.addEventListener("resize", cb);
    return () => window.removeEventListener("resize", cb);
  }, []);

  // ═══════ DOM Ladder (Left 25%) ═══════
  useEffect(() => {
    const canvas = domCanvas.current;
    if (!canvas || !l2) return;
    const ctx = canvas.getContext("2d")!;
    const dpr = window.devicePixelRatio || 1;
    const W = canvas.clientWidth;
    const H = canvas.clientHeight;
    canvas.width = W * dpr;
    canvas.height = H * dpr;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.fillStyle = BG;
    ctx.fillRect(0, 0, W, H);

    const M = { top: 20, bot: 20, left: 8, right: 4 };
    const pH = (H - M.top - M.bot) / 40; // 40 price rows
    const mid = l2.mid;
    const step = Math.max(l2.spread * 2, mid * 0.0001);
    const maxVol = Math.max(
      ...l2.bids.map(b => b.sz).slice(0, 40),
      ...l2.asks.map(a => a.sz).slice(0, 40),
      1
    );

    // Draw price ladder
    for (let i = -20; i <= 20; i++) {
      const px = mid + i * step;
      const y = M.top + (20 - i) * pH;
      const bidSz = l2.bids.find(b => Math.abs(b.px - px) < step * 0.5)?.sz ?? 0;
      const askSz = l2.asks.find(a => Math.abs(a.px - px) < step * 0.5)?.sz ?? 0;

      // Row background
      ctx.fillStyle = i === 0 ? "rgba(255,235,59,0.08)" : i % 2 ? "rgba(255,255,255,0.01)" : "transparent";
      ctx.fillRect(0, y, W, pH);

      // Bid volume bar
      if (bidSz > 0) {
        const w = (bidSz / maxVol) * W * 0.45;
        ctx.fillStyle = BID_C;
        ctx.globalAlpha = 0.25 + 0.5 * (bidSz / maxVol);
        ctx.fillRect(W * 0.05, y + 1, w, pH - 2);
      }

      // Ask volume bar
      if (askSz > 0) {
        const w = (askSz / maxVol) * W * 0.45;
        ctx.fillStyle = ASK_C;
        ctx.globalAlpha = 0.25 + 0.5 * (askSz / maxVol);
        ctx.fillRect(W * 0.55, y + 1, w, pH - 2);
      }
      ctx.globalAlpha = 1;

      // Price text
      ctx.fillStyle = i === 0 ? TXT_B : TXT;
      ctx.font = `${i === 0 ? "bold " : ""}10px "JetBrains Mono", monospace`;
      ctx.textAlign = "center";
      ctx.fillText(px.toFixed(1), W / 2, y + pH * 0.65);

      // Volume text
      ctx.font = "8px monospace";
      ctx.textAlign = "left";
      if (bidSz > 0.01) ctx.fillText(bidSz.toFixed(1), W * 0.05 + 4, y + pH * 0.65);
      ctx.textAlign = "right";
      if (askSz > 0.01) ctx.fillText(askSz.toFixed(1), W - 4, y + pH * 0.65);
    }

    // Header
    ctx.font = "9px monospace";
    ctx.textAlign = "left";
    ctx.fillText("DEPTH OF MARKET", 4, 10);
    ctx.textAlign = "right";
    ctx.fillText(`${coin}-USD`, W - 4, 10);
  }, [l2, coin, dims]);

  // ═══════ Depth Heatmap (Right 45%) ═══════
  useEffect(() => {
    const canvas = depthCanvas.current;
    if (!canvas || !l2) return;
    const ctx = canvas.getContext("2d")!;
    const dpr = window.devicePixelRatio || 1;
    const W = canvas.clientWidth;
    const H = canvas.clientHeight;
    canvas.width = W * dpr;
    canvas.height = H * dpr;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.fillStyle = PANEL_BG;
    ctx.fillRect(0, 0, W, H);

    const M = { top: 20, bot: 25, left: 40, right: 10 };
    const pW = W - M.left - M.right;
    const pH = H - M.top - M.bot;
    const mid = l2.mid;
    const range = mid * 0.02;
    const pMin = mid - range;
    const pMax = mid + range;
    const p2x = (px: number) => M.left + ((px - pMin) / (pMax - pMin)) * pW;

    // Find max vol
    const allVol = [...l2.bids.slice(0, 80), ...l2.asks.slice(0, 80)];
    const maxV = Math.max(...allVol.map(v => v.sz), 10);

    // Grid
    ctx.strokeStyle = GRID;
    ctx.lineWidth = 0.5;
    for (let i = 0; i <= 8; i++) {
      const y = M.top + (i / 8) * pH;
      ctx.beginPath(); ctx.moveTo(M.left, y); ctx.lineTo(M.left + pW, y); ctx.stroke();
    }

    // Draw cumulative volume profile
    const drawProfile = (levels: { px: number; sz: number }[], color: string, fromMid: boolean) => {
      ctx.beginPath();
      let cumVol = 0;
      const sorted = [...levels].sort((a, b) => fromMid ? b.px - a.px : a.px - b.px);
      
      // Draw filled area
      for (let i = 0; i < sorted.length; i++) {
        cumVol += sorted[i].sz;
        const x = p2x(sorted[i].px);
        const y = M.top + pH - (cumVol / maxV) * pH;
        if (i === 0) ctx.moveTo(x, M.top + pH);
        ctx.lineTo(x, y);
      }
      
      // Close and fill
      const lastX = p2x(sorted[sorted.length - 1]?.px ?? mid);
      ctx.lineTo(lastX, M.top + pH);
      ctx.closePath();
      
      const grad = ctx.createLinearGradient(0, 0, 0, H);
      grad.addColorStop(0, color + "80");
      grad.addColorStop(1, color + "10");
      ctx.fillStyle = grad;
      ctx.fill();
    };

    drawProfile(l2.bids.slice(0, 80), BID_C, true);
    drawProfile(l2.asks.slice(0, 80), ASK_C, false);

    // Mid line
    const midX = p2x(mid);
    ctx.strokeStyle = MID_C;
    ctx.lineWidth = 1.5;
    ctx.setLineDash([4, 3]);
    ctx.beginPath(); ctx.moveTo(midX, M.top); ctx.lineTo(midX, M.top + pH); ctx.stroke();
    ctx.setLineDash([]);

    // Mid price labels
    ctx.fillStyle = TXT_B;
    ctx.font = "bold 13px 'JetBrains Mono', monospace";
    ctx.textAlign = "center";
    ctx.fillText(mid.toFixed(1), midX, M.top + pH / 2 - 8);
    ctx.fillText(mid.toFixed(1), midX, M.top + pH / 2 + 20);

    // Orange mid marker
    ctx.fillStyle = "#FF9100";
    ctx.beginPath(); ctx.arc(midX, M.top + pH, 4, 0, Math.PI * 2); ctx.fill();

    // Price axis labels
    ctx.fillStyle = TXT;
    ctx.font = "8px monospace";
    ctx.textAlign = "center";
    for (let i = 0; i <= 5; i++) {
      const px = pMin + (i / 5) * (pMax - pMin);
      ctx.fillText(px.toFixed(0), p2x(px), M.top + pH + 15);
    }

    // Volume scale
    ctx.textAlign = "right";
    for (let i = 0; i <= 4; i++) {
      const v = Math.round(maxV * i / 4);
      ctx.fillText(v.toLocaleString(), M.left - 4, M.top + pH - (i / 4) * pH + 3);
    }

    // Imbalance gauge
    const imb = l2.imbalance;
    ctx.fillStyle = TXT;
    ctx.font = "9px monospace";
    ctx.textAlign = "left";
    const imbStr = `I = ${imb >= 0 ? "+" : ""}${imb.toFixed(3)}  |  (Vb-Va)/(Vb+Va)`;
    ctx.fillText(imbStr, 8, 12);

    // Spread
    ctx.textAlign = "right";
    ctx.fillText(`Spread: ${l2.spread.toFixed(1)}`, W - 8, 12);

    // Volume totals
    ctx.fillStyle = BID_C;
    ctx.textAlign = "left";
    ctx.fillText(`Bid: ${l2.totalBidVol.toFixed(1)} BTC`, 8, M.top + pH + 22);
    ctx.fillStyle = ASK_C;
    ctx.textAlign = "right";
    ctx.fillText(`Ask: ${l2.totalAskVol.toFixed(1)} BTC`, W - 8, M.top + pH + 22);
  }, [l2, dims]);

  // ═══════ Trade Tape (Bottom 30%) ═══════
  useEffect(() => {
    const canvas = tapeCanvas.current;
    if (!canvas || trades.length < 2) return;
    const ctx = canvas.getContext("2d")!;
    const dpr = window.devicePixelRatio || 1;
    const W = canvas.clientWidth;
    const H = canvas.clientHeight;
    canvas.width = W * dpr;
    canvas.height = H * dpr;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.fillStyle = PANEL_BG;
    ctx.fillRect(0, 0, W, H);

    const M = { top: 20, bot: 12, left: 40, right: 8 };
    const pW = W - M.left - M.right;
    const pH = H - M.top - M.bot;

    const prices = trades.map(t => t.px);
    const pMin = Math.min(...prices);
    const pMax = Math.max(...prices);
    const pRange = (pMax - pMin) || 1;
    const pad = pRange * 0.15 || 5;
    const pLo = pMin - pad;
    const pHi = pMax + pad;
    const p2y = (px: number) => M.top + pH - ((px - pLo) / (pHi - pLo)) * pH;

    // Grid
    ctx.strokeStyle = GRID;
    ctx.lineWidth = 0.5;
    for (let i = 0; i <= 4; i++) {
      const y = M.top + (i / 4) * pH;
      ctx.beginPath(); ctx.moveTo(M.left, y); ctx.lineTo(M.left + pW, y); ctx.stroke();
    }

    // Trade path
    ctx.strokeStyle = TRADE_C;
    ctx.lineWidth = 1.5;
    ctx.beginPath();
    for (let i = 0; i < trades.length; i++) {
      const x = M.left + (i / Math.max(trades.length - 1, 1)) * pW;
      const y = p2y(trades[i].px);
      if (i === 0) ctx.moveTo(x, y);
      else ctx.lineTo(x, y);
    }
    ctx.stroke();

    // Trade markers
    const maxSz = Math.max(...trades.map(t => t.sz), 1);
    for (let i = 0; i < trades.length; i++) {
      const t = trades[i];
      const x = M.left + (i / Math.max(trades.length - 1, 1)) * pW;
      const y = p2y(t.px);
      const r = Math.max(1.5, (t.sz / maxSz) * 4 + 1);
      ctx.fillStyle = t.side === "buy" ? "#4CAF50" : "#F44336";
      ctx.globalAlpha = 0.6;
      ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();
    }
    ctx.globalAlpha = 1;

    // Latest trade callout
    const last = trades[trades.length - 1];
    const lx = M.left + pW;
    const ly = p2y(last.px);
    ctx.fillStyle = last.side === "buy" ? "#00E676" : "#FF5252";
    ctx.font = "bold 14px 'JetBrains Mono', monospace";
    ctx.textAlign = "left";
    ctx.fillText(`${last.side === "buy" ? "B" : "S"} ${last.px.toFixed(1)}`, 8, 14);
    ctx.fillStyle = TXT;
    ctx.font = "10px monospace";
    ctx.fillText(` | ${last.sz.toFixed(4)} BTC`, 140, 14);

    // Trade count
    ctx.textAlign = "right";
    ctx.fillText(`${trades.length} trades`, W - 8, 14);

    // Price labels
    ctx.textAlign = "right";
    ctx.font = "8px monospace";
    for (let i = 0; i <= 3; i++) {
      const px = pLo + (i / 3) * (pHi - pLo);
      ctx.fillText(px.toFixed(1), M.left - 4, p2y(px) + 3);
    }
  }, [trades, dims]);

  // Has data?
  const noData = !l2 && !error;

  return (
    <div ref={containerRef} className={`relative bg-black overflow-hidden ${className}`}>
      {/* Header bar */}
      <div className="flex items-center justify-between px-4 py-2 bg-[#0D0D15] border-b border-[#1A1A2E]">
        <div className="flex items-center gap-3">
          <span className="text-xs text-gray-400 font-mono">L2 ORDER BOOK</span>
          <span className="text-[10px] text-gray-600">·</span>
          <span className="text-xs text-white font-mono font-bold">{coin}-USD</span>
          <span className="text-[10px] text-gray-600">·</span>
          <span className={`w-2 h-2 rounded-full ${connected ? "bg-green-500" : "bg-red-500"}`} />
          <span className="text-[10px] text-gray-500">{connected ? "LIVE" : "RECONNECTING"}</span>
        </div>
        <div className="flex items-center gap-4">
          {l2 && (
            <>
              <span className="text-[10px] text-gray-500">Mid</span>
              <span className="text-xs text-white font-mono font-bold">{l2.mid.toFixed(1)}</span>
              <span className="text-[10px] text-gray-500">Spread</span>
              <span className="text-xs text-white font-mono">{l2.spread.toFixed(1)}</span>
              <span className="text-[10px] text-gray-500">Imb</span>
              <span className={`text-xs font-mono ${l2.imbalance >= 0 ? "text-green-400" : "text-red-400"}`}>
                {l2.imbalance >= 0 ? "+" : ""}{l2.imbalance.toFixed(3)}
              </span>
            </>
          )}
          <span className="text-[10px] text-gray-500">Trades</span>
          <span className="text-xs text-white font-mono">{trades.length}</span>
        </div>
      </div>

      {/* Main grid: DOM Ladder | Depth Heatmap */}
      <div className="flex" style={{ height: dims.h * 0.70 }}>
        {/* DOM Ladder - 25% */}
        <div className="w-[25%] border-r border-[#1A1A2E] relative">
          <canvas ref={domCanvas} className="w-full h-full" />
          {noData && <div className="absolute inset-0 flex items-center justify-center"><span className="text-gray-600 text-xs">Waiting for L2...</span></div>}
        </div>
        {/* Depth Heatmap - 75% */}
        <div className="w-[75%] relative">
          <canvas ref={depthCanvas} className="w-full h-full" />
          {noData && <div className="absolute inset-0 flex items-center justify-center"><span className="text-gray-600 text-xs">Waiting for L2...</span></div>}
        </div>
      </div>

      {/* Bottom: Trade Tape */}
      <div className="border-t border-[#1A1A2E]" style={{ height: dims.h * 0.30 }}>
        <canvas ref={tapeCanvas} className="w-full h-full" />
        {trades.length < 2 && !error && (
          <div className="absolute inset-0 flex items-center justify-center" style={{ bottom: dims.h * 0.15 }}>
            <span className="text-gray-600 text-xs">Waiting for trades...</span>
          </div>
        )}
      </div>

      {/* Error banner */}
      {error && (
        <div className="absolute bottom-0 left-0 right-0 bg-red-900/50 text-red-300 text-[9px] px-2 py-1 font-mono">
          {error} — reconnecting every 2s
        </div>
      )}
    </div>
  );
}
