import { useMemo } from 'react';
import { CandlestickChart } from '../components/charts/CandlestickChart';
import { ComponentErrorBoundary } from '../components/common/ComponentErrorBoundary';
import { OrderBook } from '../components/trading/OrderBook';
import { PositionsTable } from '../components/trading/PositionsTable';
import { OrdersTable } from '../components/trading/OrdersTable';
import { usePositions, useOrders, useOrderBook } from '../hooks/useApi';
import { useMarketDataStream } from '../hooks/useGrpcStream';

export function TradingDashboard() {
  const positions = usePositions();
  const orders = useOrders();
  const orderBook = useOrderBook('ES.FUT');
  const { lastMessage: marketDataEvent } = useMarketDataStream();

  // Adapt proto OrderBook response to the component's expected shape
  const orderBookData = useMemo(() => {
    const ob = orderBook.data?.orderBook;
    return {
      bids: ob?.bids?.map((l) => ({ price: l.price, size: l.quantity })) ?? [],
      asks: ob?.asks?.map((l) => ({ price: l.price, size: l.quantity })) ?? [],
      spread: undefined as number | undefined,
    };
  }, [orderBook.data]);

  // Extract positions array from the gRPC response message
  const positionsList = positions.data?.positions;
  // The order response wraps a single Order; for the orders list we use
  // streamOrders or getOrderStatus which returns a single order.
  // Since the REST API returned Order[] and the proto returns a single Order,
  // we wrap it into an array for backward compatibility with OrdersTable.
  const ordersList = orders.data?.order ? [orders.data.order] : undefined;

  // We still expose lastMessage for components that might use market data
  void marketDataEvent;

  return (
    <div className="space-y-4">
      {(positions.isError || orders.isError) && (
        <div className="px-3 py-2 rounded border border-[var(--color-red)] bg-red-500/10 text-sm text-[var(--color-red)] flex items-center justify-between">
          <span>Failed to load {positions.isError ? 'positions' : 'orders'}: {(positions.error ?? orders.error)?.message}</span>
          <button onClick={() => { positions.refetch(); orders.refetch(); }} className="text-xs underline">Retry</button>
        </div>
      )}

      {/* Top row: Chart + Order Book */}
      <div className="grid grid-cols-1 lg:grid-cols-[1fr_320px] gap-4 lg:h-80">
        <div className="rounded border border-[var(--color-border)] bg-[var(--color-bg-card)] overflow-hidden">
          <ComponentErrorBoundary name="Candlestick Chart">
            <CandlestickChart symbol="ES.FUT" />
          </ComponentErrorBoundary>
        </div>
        <div className="rounded border border-[var(--color-border)] bg-[var(--color-bg-card)] overflow-hidden">
          <OrderBook
            bids={orderBookData.bids}
            asks={orderBookData.asks}
            spread={orderBookData.spread}
          />
        </div>
      </div>

      {/* Middle: Positions */}
      <div className="rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
        <PositionsTable
          positions={positionsList}
          loading={positions.isLoading}
        />
      </div>

      {/* Bottom: Orders (read-only monitoring) */}
      <div className="rounded border border-[var(--color-border)] bg-[var(--color-bg-card)]">
        <OrdersTable orders={ordersList} loading={orders.isLoading} />
      </div>
    </div>
  );
}
