import React, { memo, useState } from 'react';
import { Box, Paper, Typography, Chip, Divider, Tabs, Tab } from '@mui/material';
import {
  TrendingUp,
  TrendingDown,
  Circle as CircleIcon,
} from '@mui/icons-material';
import { OrderbookDisplayUnit, WebSocketStatus } from '../types/orderbook';

interface OrderbookProps {
  asks: OrderbookDisplayUnit[];
  bids: OrderbookDisplayUnit[];
  totalAskSize: number;
  totalBidSize: number;
  wsStatus: WebSocketStatus;
  market: string;
  bestAsk: number;
  bestBid: number;
  spread: number;
  spreadPercentage: number;
  /** 패널 임베드 시 외부 border 제거 */
  disableBorder?: boolean;
}

/**
 * 가격 포맷 (천 단위 구분)
 */
const formatPrice = (price: number): string => {
  return price.toLocaleString('ko-KR', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  });
};

/**
 * 잔량 포맷 (소수점 4자리)
 */
const formatSize = (size: number): string => {
  return size.toLocaleString('ko-KR', {
    minimumFractionDigits: 4,
    maximumFractionDigits: 4,
  });
};

/**
 * 연결 상태 아이콘 색상
 */
const getStatusColor = (status: WebSocketStatus): string => {
  switch (status) {
    case 'connected':
      return '#22c55e';
    case 'connecting':
      return '#eab308';
    case 'disconnected':
    case 'error':
      return '#ef4444';
    default:
      return '#9ca3af';
  }
};

/**
 * 호가 행 컴포넌트 (업비트 스타일: 잔량 | 가격 | 전일대비)
 */
const OrderbookRow = memo<{
  unit: OrderbookDisplayUnit;
  type: 'ask' | 'bid';
  prevPrice?: number;
}>(({ unit, type, prevPrice = 0 }) => {
  const isAsk = type === 'ask';
  const bgColor = isAsk ? 'rgba(239, 68, 68, 0.05)' : 'rgba(59, 130, 246, 0.05)';
  const barColor = isAsk ? '#ef4444' : '#3b82f6';
  const textColor = isAsk ? '#ef4444' : '#3b82f6';

  // 전일대비 계산
  const changeRate = prevPrice > 0 ? ((unit.price - prevPrice) / prevPrice) * 100 : 0;
  const changeSign = changeRate > 0 ? '+' : '';

  return (
    <Box
      sx={{
        position: 'relative',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        height: '32px',
        px: 2,
        py: 0.5,
        '&:hover': {
          backgroundColor: bgColor,
        },
        transition: 'background-color 0.2s ease',
      }}
    >
      {/* 배경 바 (좌측에서 시작) */}
      <Box
        sx={{
          position: 'absolute',
          top: 0,
          left: 0,
          height: '100%',
          width: `${unit.percentage}%`,
          backgroundColor: barColor,
          opacity: 0.1,
          transition: 'width 0.3s ease',
        }}
      />

      {/* 잔량 (좌측) */}
      <Typography
        variant="body2"
        sx={{
          position: 'relative',
          zIndex: 1,
          color: 'text.primary',
          fontFamily: 'monospace',
          fontSize: '13px',
          minWidth: '80px',
          textAlign: 'left',
        }}
      >
        {formatSize(unit.size)}
      </Typography>

      {/* 가격 (중앙) */}
      <Typography
        variant="body2"
        sx={{
          position: 'relative',
          zIndex: 1,
          fontWeight: 700,
          color: textColor,
          fontFamily: 'monospace',
          fontSize: '14px',
          flex: 1,
          textAlign: 'center',
        }}
      >
        {formatPrice(unit.price)}
      </Typography>

      {/* 전일대비 (우측) */}
      <Typography
        variant="caption"
        sx={{
          position: 'relative',
          zIndex: 1,
          color: textColor,
          fontFamily: 'monospace',
          fontSize: '12px',
          minWidth: '70px',
          textAlign: 'right',
          fontWeight: 600,
        }}
      >
        {changeSign}{Math.abs(changeRate).toFixed(2)}%
      </Typography>
    </Box>
  );
});

OrderbookRow.displayName = 'OrderbookRow';

/**
 * 호가창 메인 컴포넌트
 */
export const Orderbook = memo<OrderbookProps>(({
  asks,
  bids,
  totalAskSize,
  totalBidSize,
  wsStatus,
  market,
  bestAsk,
  bestBid,
  spread,
  spreadPercentage,
  disableBorder = false,
}) => {
  const [tabValue, setTabValue] = useState(0);
  return (
    <Paper
      elevation={0}
      sx={{
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        border: disableBorder ? 'none' : '1px solid',
        borderColor: 'divider',
        overflow: 'hidden',
        borderRadius: disableBorder ? 0 : undefined,
      }}
    >
      {/* 헤더 */}
      <Box
        sx={{
          borderBottom: 1,
          borderColor: 'divider',
        }}
      >
        <Box
          sx={{
            px: 2,
            pt: 2,
            pb: 1,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
            <Typography variant="h6" fontWeight={700}>
              호가
            </Typography>
            <Chip
              label={market}
              size="small"
              sx={{
                fontWeight: 600,
                backgroundColor: 'primary.main',
                color: 'white',
              }}
            />
          </Box>

          {/* 연결 상태 */}
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <CircleIcon
              sx={{
                fontSize: 10,
                color: getStatusColor(wsStatus),
              }}
            />
            <Typography variant="caption" color="text.secondary">
              {wsStatus === 'connected' && '연결됨'}
              {wsStatus === 'connecting' && '연결 중...'}
              {wsStatus === 'disconnected' && '연결 끊김'}
              {wsStatus === 'error' && '오류'}
            </Typography>
          </Box>
        </Box>

        {/* 탭 */}
        <Tabs
          value={tabValue}
          onChange={(_, newValue) => setTabValue(newValue)}
          variant="fullWidth"
          sx={{
            minHeight: 40,
            '& .MuiTab-root': {
              minHeight: 40,
              py: 1,
              fontSize: '0.875rem',
            },
          }}
        >
          <Tab label="일반호가" />
          <Tab label="누적호가" />
          <Tab label="호가주문" />
          <Tab label="모아보기" />
        </Tabs>
      </Box>

      {/* 호가 컨텐츠 */}
      <Box sx={{ flex: 1, overflow: 'auto', display: 'flex', flexDirection: 'column' }}>
        {/* 컬럼 헤더 */}
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            px: 2,
            py: 1,
            backgroundColor: 'background.default',
            borderBottom: 1,
            borderColor: 'divider',
          }}
        >
          <Typography variant="caption" color="text.secondary" sx={{ minWidth: '80px', textAlign: 'left' }}>
            잔량
          </Typography>
          <Typography variant="caption" color="text.secondary" sx={{ flex: 1, textAlign: 'center' }}>
            가격
          </Typography>
          <Typography variant="caption" color="text.secondary" sx={{ minWidth: '70px', textAlign: 'right' }}>
            전일대비
          </Typography>
        </Box>

        {/* 매도 호가 (15호가 → 1호가) */}
        <Box sx={{ flex: 1 }}>
          {asks.length > 0 ? (
            asks.map((ask, index) => (
              <OrderbookRow key={`ask-${ask.price}-${index}`} unit={ask} type="ask" />
            ))
          ) : (
            <Box sx={{ p: 2, textAlign: 'center' }}>
              <Typography variant="body2" color="text.secondary">
                데이터 로딩 중...
              </Typography>
            </Box>
          )}
        </Box>

        {/* 스프레드 구분선 */}
        <Divider sx={{ borderColor: 'divider', borderWidth: 1 }} />

        {/* 매수 호가 (1호가 → 15호가) */}
        <Box sx={{ flex: 1 }}>
          {bids.length > 0 ? (
            bids.map((bid, index) => (
              <OrderbookRow key={`bid-${bid.price}-${index}`} unit={bid} type="bid" />
            ))
          ) : (
            <Box sx={{ p: 2, textAlign: 'center' }}>
              <Typography variant="body2" color="text.secondary">
                데이터 로딩 중...
              </Typography>
            </Box>
          )}
        </Box>

      </Box>
    </Paper>
  );
});

Orderbook.displayName = 'Orderbook';

export default Orderbook;
