"use client";

import { useState, useEffect, useCallback } from "react";

import { CandlestickChart } from "@/components/charts/CandlestickChart";
import { DepthChart } from "@/components/charts/DepthChart";
import { OrderForm } from "@/components/trading/OrderForm";
import { PositionTable } from "@/components/trading/PositionTable";
import { OrderBook } from "@/components/trading/OrderBook";
import { RecentTrades } from "@/components/trading/RecentTrades";
import { PendingOrders } from "@/components/trading/PendingOrders";
import { useMarketData } from "@/hooks/useMarketData";
import { useOrderBook } from "@/hooks/useOrderBook";
import { useRecentTrades } from "@/hooks/useRecentTrades";
import type { TradingMode, Position, Order, Kline } from "@/types/models";

// Mock data generators for demo
function generateMockKlines(symbol: string, count: number = 100): Kline[] {
  const data: Kline[] = [];
  let basePrice = symbol.includes("BTC")
    ? 65000
    : symbol.includes("ETH")
      ? 3500
      : 100;
  const now = Date.now();

  for (let i = count; i >= 0; i--) {
    const volatility = 0.02; // 2% volatility
    const change = (Math.random() - 0.5) * volatility;
    const open = basePrice;
    const close = basePrice * (1 + change);
    const minPrice = Math.min(open, close);
    const maxPrice = Math.max(open, close);
    const low = minPrice * (1 - Math.random() * 0.005);
    const high = maxPrice * (1 + Math.random() * 0.005);
    const volume = Math.random() * 100 + 10;
    const quoteVolume = volume * close;

    data.push({
      timestamp: new Date(now - i * 60000).toISOString(),
      open,
      high,
      low,
      close,
      volume,
      quoteVolume,
    });

    basePrice = close;
  }

  return data;
}

function generateMockPositions(): Position[] {
  return [
    {
      id: "pos-1",
      symbol: "BTCUSDT",
      side: "long",
      quantity: 0.5,
      entryPrice: 64200,
      markPrice: 65100,
      liquidationPrice: 50000,
      margin: 32100,
      leverage: 1,
      unrealizedPnl: 450,
      unrealizedPnlPercent: 1.4,
      realizedPnl: 0,
      openedAt: new Date(Date.now() - 86400000).toISOString(),
    },
    {
      id: "pos-2",
      symbol: "ETHUSDT",
      side: "long",
      quantity: 2,
      entryPrice: 3450,
      markPrice: 3520,
      liquidationPrice: 2000,
      margin: 6900,
      leverage: 1,
      unrealizedPnl: 140,
      unrealizedPnlPercent: 2.03,
      realizedPnl: 0,
      openedAt: new Date(Date.now() - 172800000).toISOString(),
    },
  ];
}

function generateMockPendingOrders(): Order[] {
  return [
    {
      id: "order-1",
      symbol: "BTCUSDT",
      type: "limit",
      side: "buy",
      price: 64000,
      quantity: 0.1,
      filledQuantity: 0,
      status: "open",
      timestamp: new Date(Date.now() - 3600000).toISOString(),
    },
  ];
}

const AVAILABLE_SYMBOLS = ["BTCUSDT", "ETHUSDT", "SOLUSDT", "BNBUSDT"];

export default function Trading() {
  const [tradingMode, setTradingMode] = useState<TradingMode>("simulation");
  const [selectedSymbol, setSelectedSymbol] = useState("BTCUSDT");
  const [currentPrice, setCurrentPrice] = useState(65100);
  const [availableBalance] = useState(50000);

  // Data states
  const [klines, setKlines] = useState<Kline[]>([]);
  const [positions, setPositions] = useState<Position[]>([]);
  const [pendingOrders, setPendingOrders] = useState<Order[]>([]);

  // WebSocket hooks
  const { isConnected, isConnecting } = useMarketData({
    symbol: selectedSymbol,
    enabled: true,
  });

  const { bids, asks } = useOrderBook({ symbol: selectedSymbol });
  const { trades } = useRecentTrades({ symbol: selectedSymbol });

  // Load initial data
  useEffect(() => {
    setKlines(generateMockKlines(selectedSymbol));
    setPositions(generateMockPositions());
    setPendingOrders(generateMockPendingOrders());
  }, [selectedSymbol]);

  // Simulate price updates
  useEffect(() => {
    if (trades.length > 0) {
      setCurrentPrice(trades[0].price);
    }
  }, [trades]);

  const handleSubmitOrder = useCallback(
    async (
      order: Omit<Order, "id" | "status" | "timestamp" | "filledQuantity">,
    ) => {
      // Mock order submission
      const newOrder: Order = {
        ...order,
        id: `order-${Date.now()}`,
        status: "open",
        timestamp: new Date().toISOString(),
        filledQuantity: 0,
      };
      setPendingOrders((prev) => [...prev, newOrder]);
      alert(
        `Order Submitted: ${order.side.toUpperCase()} ${order.quantity} ${order.symbol}`,
      );
    },
    [],
  );

  const handleClosePosition = useCallback((positionId: string) => {
    setPositions((prev) => prev.filter((p) => p.id !== positionId));
  }, []);

  const handleCancelOrder = useCallback((orderId: string) => {
    setPendingOrders((prev) => prev.filter((o) => o.id !== orderId));
  }, []);

  return (
    <div className="flex flex-col gap-4 pb-6">
      {/* Header: Symbol Selector + Trading Mode + Connection Status */}
      <div className="flex flex-wrap items-center justify-between gap-4 bg-[#1e1e1e] p-4 border border-[#2c2c2c] rounded-xl">
        <div className="flex items-center gap-4">
          {/* Symbol Selector */}
          <select
            value={selectedSymbol}
            onChange={(e) => setSelectedSymbol(e.target.value)}
            className="bg-[#2c2c2c]/30 border border-[#2c2c2c] rounded-lg px-4 py-2 text-[#e1e1e1] font-bold focus:outline-none focus:border-[#00ffcc] appearance-none cursor-pointer"
          >
            {AVAILABLE_SYMBOLS.map((symbol) => (
              <option key={symbol} value={symbol}>
                {symbol}
              </option>
            ))}
          </select>

          {/* Trading Mode Toggle */}
          <div className="flex items-center gap-1 bg-[#2c2c2c]/30 rounded-lg p-1 border border-[#2c2c2c]">
            <button
              onClick={() => setTradingMode("simulation")}
              className={`px-4 py-1.5 rounded-md text-xs font-bold uppercase tracking-wider transition-all duration-200 ${
                tradingMode === "simulation"
                  ? "bg-[#00ffcc] text-[#121212]"
                  : "text-[#a0a0a0] hover:text-[#e1e1e1]"
              }`}
            >
              模拟
            </button>
            <button
              onClick={() => setTradingMode("live")}
              className={`px-4 py-1.5 rounded-md text-xs font-bold uppercase tracking-wider transition-all duration-200 ${
                tradingMode === "live"
                  ? "bg-[#00ffcc] text-[#121212]"
                  : "text-[#a0a0a0] hover:text-[#e1e1e1]"
              }`}
            >
              实盘
            </button>
          </div>

          {/* Connection Status */}
          <div className="flex items-center gap-2 text-xs">
            <span
              className={`w-2 h-2 rounded-full ${
                isConnected
                  ? "bg-[#00ffcc] shadow-[0_0_8px_rgba(0,255,204,0.5)]"
                  : isConnecting
                    ? "bg-[#ffb74d] animate-pulse"
                    : "bg-[#ff5252]"
              }`}
            />
            <span className="text-[#a0a0a0] font-bold uppercase tracking-tighter">
              {isConnected ? "已连接" : isConnecting ? "重连中" : "离线"}
            </span>
          </div>
        </div>

        {/* Current Price Display */}
        <div className="text-right">
          <div className="text-2xl font-black text-[#e1e1e1] tracking-tight">
            $
            {currentPrice.toLocaleString(undefined, {
              minimumFractionDigits: 2,
            })}
          </div>
          <div className="text-xs font-bold text-[#00ffcc] uppercase">
            +2.34% ↑
          </div>
        </div>
      </div>

      {/* Main Trading Layout */}
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-4 items-start">
        {/* Left: Chart Area (2 columns) */}
        <div className="xl:col-span-2 space-y-4">
          {/* Candlestick Chart */}
          <CandlestickChart
            data={klines}
            symbol={selectedSymbol}
            height={400}
          />

          {/* Depth Chart */}
          <DepthChart bids={bids} asks={asks} height={200} />
        </div>

        {/* Right: Order Book + Order Form + Positions */}
        <div className="space-y-4">
          {/* Order Book */}
          <div className="bg-[#1e1e1e] border border-[#2c2c2c] rounded-xl overflow-hidden">
            <div className="px-4 py-3 border-b border-[#2c2c2c]">
              <h3 className="text-sm font-semibold text-[#e1e1e1]">订单簿</h3>
            </div>
            <div className="p-4">
              <OrderBook symbol={selectedSymbol} maxRows={15} />
            </div>
          </div>
          {/* Order Form */}
          <div className="bg-[#1e1e1e] border border-[#2c2c2c] rounded-xl overflow-hidden">
            <div className="px-4 py-3 border-b border-[#2c2c2c]">
              <h3 className="text-sm font-semibold text-[#e1e1e1]">下单</h3>
            </div>
            <div className="p-4">
              <OrderForm
                symbols={AVAILABLE_SYMBOLS}
                selectedSymbol={selectedSymbol}
                onSymbolChange={setSelectedSymbol}
                availableBalance={availableBalance}
                currentPrice={currentPrice}
                onSubmitOrder={handleSubmitOrder}
              />
            </div>
          </div>

          {/* Positions */}
          <div className="bg-[#1e1e1e] border border-[#2c2c2c] rounded-xl overflow-hidden">
            <div className="px-4 py-3 border-b border-[#2c2c2c]">
              <h3 className="text-sm font-semibold text-[#e1e1e1]">当前持仓</h3>
            </div>
            <div className="p-4">
              <PositionTable
                positions={positions}
                onClosePosition={handleClosePosition}
              />
            </div>
          </div>
        </div>
      </div>

      {/* Bottom: Recent Trades + Pending Orders */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-stretch">
        <RecentTrades symbol={selectedSymbol} maxTrades={20} />
        <PendingOrders
          orders={pendingOrders}
          onCancelOrder={handleCancelOrder}
        />
      </div>
    </div>
  );
}
