import React, { useMemo } from 'react';
import TradeOrderbookPanelContent from '../../components/trade/TradeOrderbookPanelContent';
import { useUpbitOrderbook } from '../../hooks/useUpbitOrderbook';
import { useUpbitRecentTrades } from '../../hooks/useUpbitRecentTrades';
import { useWidgetDashboard, useWidgetOrderbookFillHandler } from '../WidgetDashboardContext';

/** 호가 — TradeOrderbookPanelContent 재사용 */
const OrderbookWidgetHost: React.FC = () => {
  const { selectedMarket, tickers } = useWidgetDashboard();
  const onRowClick = useWidgetOrderbookFillHandler();
  const { orderbook, wsStatus: obWsStatus, spread } = useUpbitOrderbook(selectedMarket);
  const { trades: recentTrades, strength: tradeStrength } = useUpbitRecentTrades(selectedMarket);
  const selectedTicker = tickers.get(selectedMarket);
  const orderbookPrevClose = selectedTicker
    ? (selectedTicker.tradePrice ?? 0) - (selectedTicker.changePrice ?? 0)
    : 0;
  const orderbookTickerInfo = selectedTicker ? {
    tradePrice: selectedTicker.tradePrice,
    changeRate: selectedTicker.changeRate,
    changePrice: selectedTicker.changePrice,
    accTradePrice24: selectedTicker.accTradePrice24,
    accTradeVolume24: selectedTicker.accTradeVolume24,
    highPrice: selectedTicker.highPrice,
    lowPrice: selectedTicker.lowPrice,
    openingPrice: selectedTicker.openingPrice,
  } : undefined;

  return (
    <div className="wd-widget-host wd-widget-host--orderbook">
      <TradeOrderbookPanelContent
        market={selectedMarket}
        asks={orderbook.asks}
        bids={orderbook.bids}
        totalAskSize={orderbook.totalAskSize}
        totalBidSize={orderbook.totalBidSize}
        wsStatus={obWsStatus}
        bestAsk={spread.bestAsk}
        bestBid={spread.bestBid}
        spread={spread.spread}
        spreadPct={spread.pct}
        prevClose={orderbookPrevClose}
        tickerInfo={orderbookTickerInfo}
        recentTrades={recentTrades}
        tradeStrength={tradeStrength ?? undefined}
        onRowClick={onRowClick}
      />
    </div>
  );
};

export default OrderbookWidgetHost;
