import { useState, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  Box,
  Paper,
  Typography,
  Grid,
  Button,
  TextField,
  Chip,
  Card,
  CardContent,
  Divider,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Switch,
  FormControlLabel,
  Autocomplete,
} from '@mui/material'
import {
  PlayArrow,
  Stop,
  Refresh,
  Psychology,
  AutoMode,
  TrendingUp,
  TrendingDown,
} from '@mui/icons-material'
import { autopilotApi } from '../api/autopilot'
import { tradingApi } from '../api/trading'
import { strategiesApi } from '../api/strategies'
import { marketDataApi } from '../api/marketData'
import Chart from '../components/Chart'
import { OrderSide, OrderStatus, PositionResponse, OrderResponse } from '../types'
import { useSnackbar } from '../contexts/SnackbarContext'
import { useAutopilotSettings } from '../contexts/AutopilotSettingsContext'
import { useWebSocketContext } from '../components/WebSocketProvider'
import SystemHealth from '../components/SystemHealth'
import StatusIndicator from '../components/StatusIndicator'
import DataFreshness from '../components/DataFreshness'
import LoadingSkeleton from '../components/LoadingSkeleton'
import ErrorDisplay from '../components/ErrorDisplay'
import OperationsPanel from '../components/OperationsPanel'
import RealtimePrice from '../components/RealtimePrice'
import ProviderStatusDisplay from '../components/ProviderStatus'
import ChartGrid from '../components/ChartGrid'
import { formatTime } from '../utils/formatters'
import { settingsApi } from '../api/settings'

const CRYPTO_PAIRS = [
  'BTC/USD',
  'ETH/USD',
  'BTC/USDT',
  'ETH/USDT',
  'SOL/USD',
  'ADA/USD',
  'XRP/USD',
  'DOGE/USD',
  'DOT/USD',
  'MATIC/USD',
  'AVAX/USD',
  'LINK/USD',
  'AVAX/USD',
  'SOL/USD',
]

export default function DashboardPage() {
  const queryClient = useQueryClient()
  const { showSuccess, showError } = useSnackbar()
  const { isConnected: wsConnected } = useWebSocketContext()

  // Core state
  const [selectedSymbols, setSelectedSymbols] = useState<string[]>(['BTC/USD'])
  const [symbol, setSymbol] = useState('BTC/USD') // Primary symbol for chart display
  const [paperTrading, setPaperTrading] = useState(true)
  const [optimisticRunning, setOptimisticRunning] = useState<boolean | null>(null) // For immediate UI feedback

  // Autopilot settings from context
  const autopilotSettings = useAutopilotSettings()
  const autoExecute = autopilotSettings.autoExecute
  const timeframe = autopilotSettings.timeframe
  const autopilotMode = 'intelligent' as const // Only intelligent mode is supported

  // Unified Autopilot Status Query (intelligent mode only)
  const { data: unifiedStatus, error: unifiedStatusError } = useQuery({
    queryKey: ['unified-autopilot-status', symbol, timeframe],
    queryFn: () => autopilotApi.getUnifiedStatus(symbol, autopilotMode, timeframe),
    refetchInterval: 5000,
    enabled: true,
  })

  // Use unified status for intelligent mode
  const status = unifiedStatus
  const statusError = unifiedStatusError

  // Market Data Query
  const { data: ohlcv, isLoading: isLoadingOHLCV } = useQuery({
    queryKey: ['market-data', symbol],
    queryFn: () => marketDataApi.getOHLCV(symbol),
    refetchInterval: 60000,
    retry: false,
  })

  // Positions Query
  const { data: positions } = useQuery({
    queryKey: ['positions', paperTrading],
    queryFn: () => tradingApi.getPositions(paperTrading),
    refetchInterval: 5000,
  })

  // Orders Query
  const { data: orders } = useQuery({
    queryKey: ['orders', paperTrading],
    queryFn: () => tradingApi.getOrders(paperTrading, 10),
    refetchInterval: 5000,
  })

  // General Settings for timezone and display preferences
  const { data: generalSettings } = useQuery({
    queryKey: ['general-settings'],
    queryFn: () => settingsApi.getGeneralSettings(),
  })

  // Balance Query
  const { data: balance } = useQuery({
    queryKey: ['balance', paperTrading],
    queryFn: () => tradingApi.getBalance(paperTrading),
    refetchInterval: 5000,
  })



  // Multi-Symbol Status Query
  const { data: multiSymbolStatus } = useQuery({
    queryKey: ['multi-symbol-status', autopilotMode, timeframe],
    queryFn: () => autopilotApi.getMultiSymbolStatus(undefined, autopilotMode, timeframe),
    refetchInterval: 5000,
  })

  // Running Manual Strategies Query
  const { data: runningStrategies } = useQuery({
    queryKey: ['running-strategies'],
    queryFn: () => strategiesApi.getRunningStrategies(),
    refetchInterval: 5000,
  })

  // Sync selected symbols with running autopilots AND manual strategies
  const [hasInitialized, setHasInitialized] = useState(false)
  useEffect(() => {
    if (!hasInitialized && multiSymbolStatus?.symbols && runningStrategies?.strategies) {
      // Get autopilot symbols
      const autopilotSymbols = multiSymbolStatus.symbols
        .filter(s => s.running)
        .map(s => s.symbol)

      // Get manual strategy symbols
      const manualSymbols = runningStrategies.strategies
        .filter(s => s.running && s.symbol)
        .map(s => s.symbol as string)

      // Combine and deduplicate
      const allActiveSymbols = Array.from(new Set([...autopilotSymbols, ...manualSymbols]))

      if (allActiveSymbols.length > 0) {
        // If current selections are just the default or empty, override them
        // Or if we haven't initialized yet
        if (!hasInitialized || (selectedSymbols.length === 1 && selectedSymbols[0] === 'BTC/USD')) {
          setSelectedSymbols(allActiveSymbols)
          setSymbol(allActiveSymbols[0]) // Set primary symbol for chart
        }
      }
      setHasInitialized(true)
    }
  }, [multiSymbolStatus, runningStrategies, hasInitialized])

  // Unified Autopilot Mutations
  const startUnifiedMutation = useMutation({
    mutationFn: autopilotApi.startUnified,
    onMutate: () => {
      setOptimisticRunning(true) // Immediately show as running
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['unified-autopilot-status'] })
      queryClient.invalidateQueries({ queryKey: ['autopilot-status'] })
      queryClient.invalidateQueries({ queryKey: ['intelligent-autopilot-status'] })
      showSuccess(`Autopilot started in ${autopilotMode} mode`)
    },
    onError: (error: any) => {
      setOptimisticRunning(null) // Reset on error
      const errorMessage = error?.response?.data?.detail || error?.message || 'Unknown error'
      showError(`Failed to start autopilot: ${errorMessage}`)
    },
    onSettled: () => {
      // Reset optimistic state after query refetches
      setTimeout(() => setOptimisticRunning(null), 1000)
    },
  })

  const stopUnifiedMutation = useMutation({
    mutationFn: ({ symbol, mode, timeframe }: { symbol: string; mode: 'intelligent'; timeframe: string }) =>
      autopilotApi.stopUnified(symbol, mode, timeframe),
    onMutate: () => {
      setOptimisticRunning(false) // Immediately show as stopped
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['unified-autopilot-status'] })
      queryClient.invalidateQueries({ queryKey: ['autopilot-status'] })
      queryClient.invalidateQueries({ queryKey: ['intelligent-autopilot-status'] })
      showSuccess('Autopilot stopped')
    },
    onError: (error: any) => {
      setOptimisticRunning(null) // Reset on error
      const errorMessage = error?.response?.data?.detail || error?.message || 'Unknown error'
      showError(`Failed to stop autopilot: ${errorMessage}`)
    },
    onSettled: () => {
      setTimeout(() => setOptimisticRunning(null), 1000)
    },
  })



  // Multi-symbol mutations
  const startMultiSymbolMutation = useMutation({
    mutationFn: autopilotApi.startMultiSymbol,
    onMutate: () => {
      setOptimisticRunning(true) // Immediately show as running
    },
    onSuccess: (data) => {
      const started = data.symbols.filter(s => s.status === 'started').length
      showSuccess(`Started autopilot for ${started} symbol(s)`)
      queryClient.invalidateQueries({ queryKey: ['multi-symbol-status'] })
    },
    onError: (error: any) => {
      setOptimisticRunning(null) // Reset on error
      showError(`Failed to start: ${error.message}`)
    },
    onSettled: () => {
      setTimeout(() => setOptimisticRunning(null), 1000)
    },
  })

  const stopMultiSymbolMutation = useMutation({
    mutationFn: ({ symbols, mode, timeframe }: { symbols: string[]; mode: string; timeframe: string }) =>
      autopilotApi.stopMultiSymbol(symbols, mode, timeframe),
    onMutate: () => {
      setOptimisticRunning(false) // Immediately show as stopped
    },
    onSuccess: (data) => {
      showSuccess(`Stopped ${data.symbols.length} symbol(s)`)
      queryClient.invalidateQueries({ queryKey: ['multi-symbol-status'] })
    },
    onError: (error: any) => {
      setOptimisticRunning(null) // Reset on error
      showError(`Failed to stop: ${error.message}`)
    },
    onSettled: () => {
      setTimeout(() => setOptimisticRunning(null), 1000)
    },
  })

  const handleStartUnifiedAutopilot = () => {
    // Use multi-symbol start if multiple symbols selected
    if (selectedSymbols.length > 0) {
      startMultiSymbolMutation.mutate({
        symbols: selectedSymbols,
        mode: 'intelligent', // Enforce intelligent mode
        auto_execute: autoExecute,
        timeframe,
        exchange_id: autopilotSettings.exchange_id,
        paper_trading: paperTrading,
        interval: autopilotSettings.interval,
      })
    } else {
      startUnifiedMutation.mutate({
        symbol,
        mode: autopilotMode,
        auto_execute: autoExecute,
        interval: autopilotSettings.interval,
        exchange_id: autopilotSettings.exchange_id,
        timeframe,
        paper_trading: paperTrading,
      })
    }
  }

  const handleStopUnifiedAutopilot = () => {
    // Stop all running symbols
    if (multiSymbolStatus && multiSymbolStatus.total_running > 0) {
      const runningSymbols = multiSymbolStatus.symbols
        .filter(s => s.running)
        .map(s => s.symbol)
      stopMultiSymbolMutation.mutate({ symbols: runningSymbols, mode: 'intelligent', timeframe })
    } else {
      stopUnifiedMutation.mutate({ symbol, mode: 'intelligent', timeframe })
    }
  }

  const getStatusColor = (orderStatus: OrderStatus) => {
    switch (orderStatus) {
      case OrderStatus.FILLED:
        return 'success'
      case OrderStatus.PENDING:
      case OrderStatus.OPEN:
        return 'warning'
      case OrderStatus.CANCELLED:
      case OrderStatus.REJECTED:
        return 'error'
      default:
        return 'default'
    }
  }

  // Use optimistic state if set, otherwise fall back to server state
  const serverRunning = unifiedStatus?.running ?? status?.running ?? false
  const isRunning = optimisticRunning !== null ? optimisticRunning : serverRunning

  return (
    <Box>
      {/* Header with controls */}
      <Paper sx={{ p: 2, mb: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 2 }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
            <Typography variant="h5" sx={{ fontWeight: 600 }}>Dashboard</Typography>
            <Chip
              label={isRunning ? `AutoPilot Active (${autopilotMode})` : 'AutoPilot Stopped'}
              color={isRunning ? 'success' : 'default'}
              size="small"
            />
            {isRunning && autoExecute && (
              <Chip
                label="Auto-Execute Enabled"
                color="warning"
                size="small"
              />
            )}
          </Box>

          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
            {/* Multi-Symbol Selector */}
            <Autocomplete
              multiple
              size="small"
              options={CRYPTO_PAIRS}
              value={selectedSymbols}
              onChange={(_, newValue) => {
                setSelectedSymbols(newValue)
                if (newValue.length > 0) {
                  setSymbol(newValue[0]) // Set primary symbol for chart
                }
              }}
              renderTags={(value, getTagProps) =>
                value.map((option, index) => (
                  <Chip
                    variant="outlined"
                    label={option}
                    size="small"
                    {...getTagProps({ index })}
                    key={option}
                  />
                ))
              }
              renderInput={(params) => (
                <TextField
                  {...params}
                  label="Trading Symbols"
                  placeholder={selectedSymbols.length === 0 ? "Select symbols..." : ""}
                />
              )}
              sx={{ minWidth: 280 }}
            />

            {/* Paper/Real Toggle */}
            <FormControlLabel
              control={
                <Switch
                  checked={!paperTrading}
                  onChange={(e) => setPaperTrading(!e.target.checked)}
                  color="warning"
                />
              }
              label={
                <Typography variant="body2" sx={{ fontWeight: 500 }}>
                  {paperTrading ? 'Paper' : 'Real'}
                </Typography>
              }
            />

            {/* AutoPilot Toggle Button */}
            <Button
              variant={isRunning || (multiSymbolStatus?.total_running || 0) > 0 ? "contained" : "outlined"}
              color={isRunning || (multiSymbolStatus?.total_running || 0) > 0 ? "success" : "inherit"}
              startIcon={isRunning || (multiSymbolStatus?.total_running || 0) > 0 ? <Stop /> : <PlayArrow />}
              onClick={isRunning || (multiSymbolStatus?.total_running || 0) > 0
                ? handleStopUnifiedAutopilot
                : handleStartUnifiedAutopilot}
              disabled={
                (isRunning || (multiSymbolStatus?.total_running || 0) > 0)
                  ? stopMultiSymbolMutation.isPending
                  : (startMultiSymbolMutation.isPending || selectedSymbols.length === 0)
              }
              sx={{
                minWidth: 180,
                fontWeight: 600,
                transition: 'all 0.3s ease',
                ...(isRunning || (multiSymbolStatus?.total_running || 0) > 0 ? {
                  backgroundColor: '#4caf50',
                  '&:hover': {
                    backgroundColor: '#388e3c',
                  },
                  boxShadow: '0 0 12px rgba(76, 175, 80, 0.4)',
                } : {
                  borderColor: 'rgba(255,255,255,0.3)',
                  color: 'text.secondary',
                  '&:hover': {
                    borderColor: 'primary.main',
                    color: 'primary.main',
                  },
                }),
              }}
            >
              {isRunning || (multiSymbolStatus?.total_running || 0) > 0
                ? ((multiSymbolStatus?.total_running || 0) > 1
                  ? `AutoPilot ON (${multiSymbolStatus?.total_running})`
                  : 'AutoPilot ON')
                : (selectedSymbols.length > 1
                  ? `AutoPilot OFF (${selectedSymbols.length})`
                  : 'AutoPilot OFF')
              }
            </Button>
          </Box>
        </Box>
      </Paper>

      {/* System Health */}
      <Grid container spacing={3} sx={{ mb: 3 }}>
        <Grid item xs={12} md={6}>
          <SystemHealth
            websocketStatus={wsConnected ? 'connected' : 'disconnected'}
            databaseStatus="connected"
          />
        </Grid>
        <Grid item xs={12} md={6}>
          <Paper sx={{ p: 2 }}>
            <Typography variant="h6" gutterBottom>
              System Status
            </Typography>
            <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap', mt: 2, mb: 2 }}>
              <StatusIndicator
                status={wsConnected ? 'connected' : 'disconnected'}
                label={wsConnected ? 'WebSocket Connected' : 'WebSocket Disconnected'}
                tooltip={wsConnected ? 'Real-time updates active' : 'Real-time updates unavailable'}
              />
              {ohlcv && ohlcv.length > 0 && (
                <DataFreshness timestamp={new Date(ohlcv[ohlcv.length - 1].time * 1000)} />
              )}
            </Box>
            <Box sx={{ mt: 2 }}>
              <ProviderStatusDisplay compact={true} />
            </Box>
          </Paper>
        </Grid>
        <Grid item xs={12}>
          <OperationsPanel
            operations={[
              // Show all running autopilots from multi-symbol status
              ...(multiSymbolStatus?.symbols || [])
                .filter(s => s.running)
                .map((s, i) => ({
                  id: `autopilot-${s.symbol}-${i}`,
                  type: 'strategy' as const,
                  name: `AutoPilot: ${s.symbol} (${s.mode})`,
                  status: 'running' as const,
                  startTime: new Date(),
                  details: s.selected_strategy ? `Strategy: ${s.selected_strategy}` : undefined,
                })),
              // Show manually running strategies
              ...(runningStrategies?.strategies || [])
                .filter(s => s.running)
                .map((s) => ({
                  id: `manual-${s.strategy_id}`,
                  type: 'strategy' as const,
                  name: `Manual: ${s.name}`,
                  status: 'running' as const,
                  startTime: s.started_at ? new Date(s.started_at) : new Date(),
                  details: `Symbol: ${s.symbol} | Type: ${s.type}`,
                })),
              // Fallback for unified single symbol (if not covered above)
              ...(isRunning && (!multiSymbolStatus?.total_running)
                ? [{
                  id: 'autopilot-running',
                  type: 'strategy' as const,
                  name: `AutoPilot: ${symbol} (${autopilotMode})`,
                  status: 'running' as const,
                  startTime: new Date(),
                }]
                : []),
            ]}
          />
        </Grid>
      </Grid>

      {/* Error Alert */}
      {(statusError || unifiedStatusError) && (
        <ErrorDisplay
          error={(statusError || unifiedStatusError) as Error}
          title="Connection Error"
          onRetry={() => {
            queryClient.invalidateQueries({ queryKey: ['autopilot-status'] })
            queryClient.invalidateQueries({ queryKey: ['unified-autopilot-status'] })
          }}
        />
      )}

      <Grid container spacing={3}>
        {/* Left Panel - ML Autopilot Info */}
        <Grid item xs={12} md={3}>
          <Paper sx={{ p: 2, height: '100%' }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 2 }}>
              <Psychology color="primary" />
              <Typography variant="h6">ML Autopilot</Typography>
            </Box>

            {/* Active Strategy Display */}
            <Box sx={{ mb: 2, p: 1.5, bgcolor: 'action.hover', borderRadius: 1 }}>
              <Typography variant="caption" color="text.secondary">
                Active Strategy
              </Typography>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 0.5 }}>
                <AutoMode fontSize="small" color={status?.selected_strategy ? 'success' : 'disabled'} />
                <Typography variant="body1" sx={{ fontWeight: 500 }}>
                  {status?.selected_strategy
                    ? status.selected_strategy.replace(/_/g, ' ').replace(/\b\w/g, (l: string) => l.toUpperCase())
                    : 'Waiting for analysis...'}
                </Typography>
              </Box>
            </Box>

            {/* How it works */}
            <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 1 }}>
              The ML model analyzes market conditions and automatically selects the best strategy from 14 available:
            </Typography>
            <Typography variant="caption" color="text.secondary" component="div" sx={{ lineHeight: 1.8 }}>
              RSI • MACD • Moving Average • Bollinger • Momentum • DCA • Grid • Pairs Trading • Volatility Breakout • Sentiment • Market Making • Consensus • Confirmed • Divergence
            </Typography>
            <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1, fontStyle: 'italic' }}>
              Tip: Configure strategy parameters and availability in the Strategy Configurations page.
            </Typography>

            <Divider sx={{ my: 2 }} />

            {/* Balance Display */}
            <Typography variant="subtitle2" color="text.secondary" gutterBottom>
              Account Balance
            </Typography>
            <Typography variant="h5" sx={{ mb: 2 }}>
              ${balance?.balance?.toFixed(2) || '0.00'}
            </Typography>

            {/* Positions Summary */}
            <Typography variant="subtitle2" color="text.secondary" gutterBottom>
              Open Positions
            </Typography>
            {positions && positions.length > 0 ? (
              <Box>
                {positions.slice(0, 3).map((pos: PositionResponse) => (
                  <Box key={pos.symbol} sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                    <Typography variant="body2">{pos.symbol}</Typography>
                    <Typography
                      variant="body2"
                      sx={{
                        color: pos.unrealized_pnl >= 0 ? 'success.main' : 'error.main',
                        fontWeight: 500
                      }}
                    >
                      {pos.unrealized_pnl >= 0 ? '+' : ''}{pos.unrealized_pnl.toFixed(2)}
                    </Typography>
                  </Box>
                ))}
              </Box>
            ) : (
              <Typography variant="body2" color="text.secondary">No positions</Typography>
            )}
          </Paper>
        </Grid>

        {/* Charts Section */}
        <Grid item xs={12} md={selectedSymbols.length > 1 ? 9 : 6}>
          {selectedSymbols.length > 1 ? (
            // Multi-chart grid for multiple symbols
            <ChartGrid
              symbols={selectedSymbols}
              onAnalyze={() => { }}
              isAnalyzing={false}
            />
          ) : (
            // Single chart for one symbol
            <Paper sx={{ p: 2 }}>
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2, flexWrap: 'wrap', gap: 2 }}>
                <Box>
                  <Typography variant="h6" gutterBottom>{symbol}</Typography>
                  <RealtimePrice symbol={symbol} size="medium" showProvider={true} showChange={true} />
                </Box>
                <Button
                  size="small"
                  startIcon={<Refresh />}
                  onClick={() => { }} // Analysis removed
                  disabled={true}
                >
                  Analyze Now
                </Button>
              </Box>
              {isLoadingOHLCV ? (
                <LoadingSkeleton variant="card" rows={1} />
              ) : ohlcv && Array.isArray(ohlcv) && ohlcv.length > 0 ? (
                <Chart data={ohlcv} />
              ) : (
                <Box sx={{ height: 400, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Typography color="text.secondary">No market data available</Typography>
                </Box>
              )}
            </Paper>
          )}
        </Grid>

        {/* Right Panel - Status */}
        <Grid item xs={12} md={3}>
          <Grid container spacing={2} direction="column">
            {/* Signal Card */}
            <Grid item>
              <Card>
                <CardContent>
                  <Typography color="text.secondary" gutterBottom>Last Signal</Typography>
                  {status?.last_signal ? (
                    <Box>
                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                        {status.last_signal.type === 'buy' ? (
                          <TrendingUp color="success" />
                        ) : (
                          <TrendingDown color="error" />
                        )}
                        <Typography
                          variant="h4"
                          sx={{
                            color: status.last_signal.type === 'buy' ? 'success.main' : 'error.main'
                          }}
                        >
                          {status.last_signal.type?.toUpperCase()}
                        </Typography>
                      </Box>
                      <Typography variant="body2" color="text.secondary">
                        Strength: {(status.last_signal.strength * 100).toFixed(0)}%
                      </Typography>
                    </Box>
                  ) : (
                    <Typography variant="body1" color="text.secondary">
                      No signals yet
                    </Typography>
                  )}
                </CardContent>
              </Card>
            </Grid>


          </Grid>
        </Grid>

        {/* Bottom - Recent Orders */}
        <Grid item xs={12}>
          <Paper sx={{ p: 2 }}>
            <Typography variant="h6" gutterBottom>Recent Activity</Typography>
            <TableContainer>
              <Table size="small">
                <TableHead>
                  <TableRow>
                    <TableCell>Time</TableCell>
                    <TableCell>Symbol</TableCell>
                    <TableCell>Side</TableCell>
                    <TableCell>Type</TableCell>
                    <TableCell align="right">Quantity</TableCell>
                    <TableCell align="right">Price</TableCell>
                    <TableCell>Status</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {orders && orders.length > 0 ? (
                    orders.slice(0, 5).map((order: OrderResponse) => (
                      <TableRow key={order.id}>
                        <TableCell>{formatTime(order.created_at, generalSettings)}</TableCell>
                        <TableCell>{order.symbol}</TableCell>
                        <TableCell>
                          <Chip
                            label={order.side}
                            size="small"
                            color={order.side === OrderSide.BUY ? 'success' : 'error'}
                          />
                        </TableCell>
                        <TableCell>{order.order_type.replace('_', ' ')}</TableCell>
                        <TableCell align="right">{Number(order.quantity).toFixed(6)}</TableCell>
                        <TableCell align="right">
                          {order.price ? `$${Number(order.price).toFixed(2)}` : 'Market'}
                        </TableCell>
                        <TableCell>
                          <Chip
                            label={order.status}
                            size="small"
                            color={getStatusColor(order.status) as any}
                          />
                        </TableCell>
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell colSpan={7} align="center">
                        <Typography variant="body2" color="text.secondary">
                          No recent activity
                        </Typography>
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          </Paper>
        </Grid>
      </Grid>
    </Box>
  )
}
