import React, { useState, useEffect, useMemo } from 'react';
import {
  Box,
  Typography,
  Grid,
  Alert,
} from '@mui/material';
import Orderbook from '../components/Orderbook';
import MarketList from '../components/MarketList';
import { useUpbitOrderbook } from '../hooks/useUpbitOrderbook';
import { useUpbitTicker } from '../hooks/useUpbitTicker';

/**
 * 호가 페이지
 */
const OrderbookPage: React.FC = () => {
  const [selectedMarket, setSelectedMarket] = useState<string>('');
  
  // 티커 데이터 (종목 목록)
  const { tickers, wsStatus: tickerWsStatus } = useUpbitTicker();
  
  // 거래대금 순으로 정렬된 첫 번째 종목
  const firstMarket = useMemo(() => {
    const tickerArray = Array.from(tickers.values());
    if (tickerArray.length === 0) return null;
    
    // 거래대금 순으로 정렬
    const sorted = tickerArray.sort((a, b) => b.accTradePrice24h - a.accTradePrice24h);
    return sorted[0]?.code || null;
  }, [tickers]);

  // 티커 로드 후 첫 번째 종목 자동 선택
  useEffect(() => {
    if (firstMarket && !selectedMarket) {
      setSelectedMarket(firstMarket);
    }
  }, [firstMarket, selectedMarket]);
  
  // 호가 데이터 (선택된 종목)
  const { orderbook, wsStatus: orderbookWsStatus, spread } = useUpbitOrderbook(selectedMarket || 'KRW-BTC');

  const currentTicker = tickers.get(selectedMarket);

  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <Box sx={{ p: 2, borderBottom: 1, borderColor: 'divider', backgroundColor: 'background.paper' }}>
        <Typography variant="h5" component="h1" fontWeight={700}>
          실시간 호가
        </Typography>
        <Typography variant="body2" color="text.secondary">
          업비트 WebSocket을 통한 실시간 호가 정보
        </Typography>
      </Box>

      {/* Connection Status Alert */}
      {(tickerWsStatus !== 'connected' || orderbookWsStatus !== 'connected') && (
        <Alert severity="warning" sx={{ m: 2, mb: 0 }}>
          {tickerWsStatus !== 'connected' && '종목 목록 연결 중...'}
          {orderbookWsStatus !== 'connected' && ' 호가 정보 연결 중...'}
        </Alert>
      )}

      {/* Main Content */}
      <Box sx={{ flex: 1, overflow: 'hidden', p: 2 }}>
        <Grid container spacing={2} sx={{ height: '100%' }}>
          {/* 좌측: 종목 목록 (1/2 = 50%) */}
          <Grid item xs={12} sm={6} sx={{ height: '100%' }}>
            <Box sx={{ height: 'calc(100vh - 200px)' }}>
              <MarketList
                tickers={tickers}
                selectedMarket={selectedMarket}
                onSelectMarket={setSelectedMarket}
                wsStatus={tickerWsStatus}
              />
            </Box>
          </Grid>

          {/* 우측: 호가창 (1/2 = 50%) */}
          <Grid item xs={12} sm={6} sx={{ height: '100%' }}>
            <Box sx={{ height: 'calc(100vh - 200px)' }}>
              {selectedMarket && currentTicker ? (
                <Orderbook
                  asks={orderbook.asks}
                  bids={orderbook.bids}
                  totalAskSize={orderbook.totalAskSize}
                  totalBidSize={orderbook.totalBidSize}
                  wsStatus={orderbookWsStatus}
                  market={selectedMarket}
                  bestAsk={spread.bestAsk}
                  bestBid={spread.bestBid}
                  spread={spread.spread}
                  spreadPercentage={spread.spreadPercentage}
                />
              ) : (
                <Box
                  sx={{
                    height: '100%',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    border: 1,
                    borderColor: 'divider',
                    borderRadius: 1,
                  }}
                >
                  <Typography variant="body1" color="text.secondary">
                    데이터 로딩 중...
                  </Typography>
                </Box>
              )}
            </Box>
          </Grid>
        </Grid>
      </Box>
    </Box>
  );
};

export default OrderbookPage;
