import { useState, useEffect } from 'react'
import { useWebSocketContext } from '../components/WebSocketProvider'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  Box,
  Paper,
  Typography,
  Tabs,
  Tab,
  TextField,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Chip,
  Alert as MuiAlert,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Checkbox,
  FormControlLabel,
  Grid,
  IconButton,
  Switch,
  CircularProgress,
  LinearProgress,
  Divider,
  Card,
  CardContent,
  Autocomplete,
} from '@mui/material'
import { Add, Edit, Delete, CheckCircle, NotificationsActive, NotificationsOff, ExpandMore, ExpandLess, Psychology, ArrowUpward, ArrowDownward } from '@mui/icons-material'

import { settingsApi, ExchangeCreate, GeneralSettings } from '../api/settings'
import { exchangesApi } from '../api/exchanges'
import { alertsApi, AlertResponse, AlertCreate, AlertUpdate } from '../api/alerts'
import { useSnackbar } from '../contexts/SnackbarContext'
import { useAutopilotSettings, useUpdateAutopilotSettings } from '../contexts/AutopilotSettingsContext'
import { autopilotApi } from '../api/autopilot'
import AlertHistory from '../components/AlertHistory'
import StatusIndicator from '../components/StatusIndicator'

import ProviderStatusDisplay from '../components/ProviderStatus'
import { marketDataApi } from '../api/marketData'

interface TabPanelProps {
  children?: React.ReactNode
  index: number
  value: number
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props
  return (
    <div role="tabpanel" hidden={value !== index} {...other}>
      {value === index && <Box sx={{ p: 3 }}>{children}</Box>}
    </div>
  )
}

export default function SettingsPage() {
  const [tabValue, setTabValue] = useState(0)
  const [exchangeDialogOpen, setExchangeDialogOpen] = useState(false)
  const [editingExchange, setEditingExchange] = useState<any>(null)
  const queryClient = useQueryClient()
  const { showSuccess, showError, showWarning } = useSnackbar()

  // Risk Settings
  const { data: riskSettings } = useQuery({
    queryKey: ['risk-settings'],
    queryFn: settingsApi.getRiskSettings,
  })

  const riskMutation = useMutation({
    mutationFn: settingsApi.updateRiskSettings,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['risk-settings'] })
      showSuccess('Risk settings saved successfully')
    },
  })

  // Paper Trading Settings
  const { data: paperSettings } = useQuery({
    queryKey: ['paper-settings'],
    queryFn: settingsApi.getPaperTradingSettings,
  })

  const paperMutation = useMutation({
    mutationFn: settingsApi.updatePaperTradingSettings,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['paper-settings'] })
      showSuccess('Paper trading settings saved successfully')
    },
  })

  const resetPaperMutation = useMutation({
    mutationFn: settingsApi.resetPaperAccount,
    onSuccess: () => {
      showSuccess('Paper account reset successfully')
    },
  })

  // Logging Settings
  const { data: loggingSettings } = useQuery({
    queryKey: ['logging-settings'],
    queryFn: settingsApi.getLoggingSettings,
  })

  const loggingMutation = useMutation({
    mutationFn: settingsApi.updateLoggingSettings,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['logging-settings'] })
      showSuccess('Logging settings saved successfully')
    },
  })

  // Exchanges
  const { data: exchanges } = useQuery({
    queryKey: ['exchanges'],
    queryFn: exchangesApi.listExchanges,
  })

  const testConnectionMutation = useMutation({
    mutationFn: settingsApi.testExchangeConnection,
  })

  const deleteExchangeMutation = useMutation({
    mutationFn: settingsApi.deleteExchange,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['exchanges'] })
    },
  })

  const handleSaveRisk = () => {
    if (!riskSettings) return
    riskMutation.mutate(riskSettings)
  }

  const handleSavePaper = () => {
    if (!paperSettings) return
    paperMutation.mutate(paperSettings)
  }

  const handleSaveLogging = () => {
    if (!loggingSettings) return
    loggingMutation.mutate(loggingSettings)
  }

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

  const generalMutation = useMutation({
    mutationFn: settingsApi.updateGeneralSettings,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['general-settings'] })
      showSuccess('General settings saved successfully')
    },
  })

  const handleSaveGeneral = () => {
    if (!generalSettings) return
    generalMutation.mutate(generalSettings)
  }

  const handleAddExchange = () => {
    setEditingExchange(null)
    setExchangeDialogOpen(true)
  }

  const handleEditExchange = (exchange: any) => {
    setEditingExchange(exchange)
    setExchangeDialogOpen(true)
  }

  const handleDeleteExchange = (exchangeId: number) => {
    if (window.confirm('Are you sure you want to delete this exchange?')) {
      deleteExchangeMutation.mutate(exchangeId)
      showSuccess('Exchange deleted successfully')
    }
  }

  const handleTestConnection = (exchangeId: number) => {
    testConnectionMutation.mutate(exchangeId, {
      onSuccess: (data) => {
        if (data.message?.includes('success') || data.message?.includes('connected')) {
          showSuccess(data.message || 'Connection test completed successfully')
        } else {
          showWarning(data.message || 'Connection test completed with warnings')
        }
      },
      onError: (error: any) => {
        showError(error?.response?.data?.detail || error?.message || 'Connection test failed')
      },
    })
  }

  return (
    <Box>
      <Typography variant="h4" gutterBottom>
        Settings
      </Typography>

      <Paper>
        <Tabs value={tabValue} onChange={(_, v) => setTabValue(v)} variant="scrollable" scrollButtons="auto">
          <Tab label="General" />
          <Tab label="Exchanges" />
          <Tab label="Data Providers" />
          <Tab label="Risk Management" />
          <Tab label="Autopilot" />
          <Tab label="Paper Trading" />
          <Tab label="Data & Logging" />
          <Tab label="Alerts" />
          <Tab label="Alert History" />
        </Tabs>

        {/* General Tab */}
        <TabPanel value={tabValue} index={0}>
          <GeneralSettingsSection
            settings={generalSettings}
            onSave={handleSaveGeneral}
            isPending={generalMutation.isPending}
            onSettingsChange={(newSettings) => queryClient.setQueryData(['general-settings'], newSettings)}
          />
        </TabPanel>

        {/* Exchanges Tab */}
        <TabPanel value={tabValue} index={1}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
            <Typography variant="h6">Exchange Management</Typography>
            <Button variant="contained" startIcon={<Add />} onClick={handleAddExchange}>
              Add Exchange
            </Button>
          </Box>
          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>Name</TableCell>
                  <TableCell>Status</TableCell>
                  <TableCell>Mode</TableCell>
                  <TableCell>Read-Only</TableCell>
                  <TableCell align="right">Actions</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {exchanges && exchanges.length > 0 ? (
                  exchanges.map((exchange: any) => (
                    <TableRow key={exchange.id}>
                      <TableCell>{exchange.name}</TableCell>
                      <TableCell>
                        <StatusIndicator
                          status={exchange.enabled ? 'connected' : 'disconnected'}
                          label={exchange.enabled ? 'Enabled' : 'Disabled'}
                        />
                      </TableCell>
                      <TableCell>{exchange.sandbox ? 'Sandbox' : 'Live'}</TableCell>
                      <TableCell>{exchange.read_only ? 'Yes' : 'No'}</TableCell>
                      <TableCell align="right">
                        <IconButton size="small" onClick={() => handleEditExchange(exchange)}>
                          <Edit />
                        </IconButton>
                        <IconButton size="small" onClick={() => handleTestConnection(exchange.id)}>
                          <CheckCircle />
                        </IconButton>
                        <IconButton size="small" onClick={() => handleDeleteExchange(exchange.id)}>
                          <Delete />
                        </IconButton>
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={5} align="center">
                      No exchanges configured
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </TableContainer>
        </TabPanel>

        {/* Data Providers Tab */}
        <TabPanel value={tabValue} index={2}>
          <DataProvidersSection />
        </TabPanel>

        {/* Risk Management Tab */}
        <TabPanel value={tabValue} index={3}>
          <Typography variant="h6" gutterBottom>
            Risk Management Settings
          </Typography>
          {riskSettings && (
            <Grid container spacing={2} sx={{ maxWidth: 600 }}>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="Max Drawdown Limit (%)"
                  type="number"
                  value={riskSettings.max_drawdown_percent}
                  onChange={(e) => {
                    const newSettings = { ...riskSettings, max_drawdown_percent: parseFloat(e.target.value) }
                    queryClient.setQueryData(['risk-settings'], newSettings)
                  }}
                  inputProps={{ step: 0.1, min: 0.1, max: 100 }}
                />
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="Daily Loss Limit (%)"
                  type="number"
                  value={riskSettings.daily_loss_limit_percent}
                  onChange={(e) => {
                    const newSettings = { ...riskSettings, daily_loss_limit_percent: parseFloat(e.target.value) }
                    queryClient.setQueryData(['risk-settings'], newSettings)
                  }}
                  inputProps={{ step: 0.1, min: 0.1, max: 100 }}
                />
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="Default Position Size (%)"
                  type="number"
                  value={riskSettings.position_size_percent}
                  onChange={(e) => {
                    const newSettings = { ...riskSettings, position_size_percent: parseFloat(e.target.value) }
                    queryClient.setQueryData(['risk-settings'], newSettings)
                  }}
                  inputProps={{ step: 0.01, min: 0.01, max: 100 }}
                />
              </Grid>
              <Grid item xs={12}>
                <Button variant="contained" onClick={handleSaveRisk} disabled={riskMutation.isPending}>
                  Save Risk Settings
                </Button>
              </Grid>
            </Grid>
          )}
        </TabPanel>

        {/* Autopilot Tab */}
        <TabPanel value={tabValue} index={4}>
          <AutopilotSettingsSection />
        </TabPanel>

        {/* Paper Trading Tab */}
        <TabPanel value={tabValue} index={5}>
          <PaperTradingSettingsSection
            paperSettings={paperSettings}
            onSettingsChange={(newSettings) => queryClient.setQueryData(['paper-settings'], newSettings)}
            onSave={handleSavePaper}
            onReset={() => {
              if (confirm('Are you sure you want to reset the paper trading account? All positions will be closed.')) {
                resetPaperMutation.mutate()
              }
            }}
            isPending={paperMutation.isPending}
            isResetting={resetPaperMutation.isPending}
          />
        </TabPanel>

        {/* Data & Logging Tab */}
        <TabPanel value={tabValue} index={6}>
          <Typography variant="h6" gutterBottom>
            Data & Logging Settings
          </Typography>
          {loggingSettings && (
            <Grid container spacing={2} sx={{ maxWidth: 600 }}>
              <Grid item xs={12}>
                <FormControl fullWidth>
                  <InputLabel>Log Level</InputLabel>
                  <Select
                    value={loggingSettings.level}
                    label="Log Level"
                    onChange={(e) => {
                      const newSettings = { ...loggingSettings, level: e.target.value }
                      queryClient.setQueryData(['logging-settings'], newSettings)
                    }}
                  >
                    <MenuItem value="DEBUG">DEBUG</MenuItem>
                    <MenuItem value="INFO">INFO</MenuItem>
                    <MenuItem value="WARNING">WARNING</MenuItem>
                    <MenuItem value="ERROR">ERROR</MenuItem>
                    <MenuItem value="CRITICAL">CRITICAL</MenuItem>
                  </Select>
                </FormControl>
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="Log Directory"
                  value={loggingSettings.dir}
                  onChange={(e) => {
                    const newSettings = { ...loggingSettings, dir: e.target.value }
                    queryClient.setQueryData(['logging-settings'], newSettings)
                  }}
                />
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="Log Retention (days)"
                  type="number"
                  value={loggingSettings.retention_days}
                  onChange={(e) => {
                    const newSettings = { ...loggingSettings, retention_days: parseInt(e.target.value) }
                    queryClient.setQueryData(['logging-settings'], newSettings)
                  }}
                  inputProps={{ step: 1, min: 1, max: 365 }}
                />
              </Grid>
              <Grid item xs={12}>
                <Button variant="contained" onClick={handleSaveLogging} disabled={loggingMutation.isPending}>
                  Save Logging Settings
                </Button>
              </Grid>
            </Grid>
          )}
        </TabPanel>

        {/* Alerts Tab */}
        <TabPanel value={tabValue} index={7}>
          <AlertsSection />
        </TabPanel>

        {/* Alert History Tab */}
        <TabPanel value={tabValue} index={8}>
          <AlertHistory />
        </TabPanel>
      </Paper>

      {/* Exchange Dialog */}
      <ExchangeDialog
        open={exchangeDialogOpen}
        onClose={() => setExchangeDialogOpen(false)}
        exchange={editingExchange}
        onSave={() => {
          setExchangeDialogOpen(false)
          queryClient.invalidateQueries({ queryKey: ['exchanges'] })
        }}
      />
    </Box>
  )
}

// Paper Trading Settings Section
function PaperTradingSettingsSection({
  paperSettings,
  onSettingsChange,
  onSave,
  onReset,
  isPending,
  isResetting,
}: {
  paperSettings: any
  onSettingsChange: (settings: any) => void
  onSave: () => void
  onReset: () => void
  isPending: boolean
  isResetting: boolean
}) {
  // Get available fee exchanges
  const { data: feeExchanges } = useQuery({
    queryKey: ['fee-exchanges'],
    queryFn: settingsApi.getFeeExchanges,
  })

  if (!paperSettings) {
    return <CircularProgress />
  }

  return (
    <Box>
      <Typography variant="h6" gutterBottom>
        Paper Trading Settings
      </Typography>

      <Grid container spacing={3} sx={{ maxWidth: 700 }}>
        {/* Initial Capital */}
        <Grid item xs={12} sm={6}>
          <TextField
            fullWidth
            label="Initial Capital ($)"
            type="number"
            value={paperSettings.initial_capital}
            onChange={(e) => {
              onSettingsChange({ ...paperSettings, initial_capital: parseFloat(e.target.value) })
            }}
            inputProps={{ step: 100, min: 1, max: 1000000 }}
          />
        </Grid>

        {/* Fee Exchange Selector */}
        <Grid item xs={12} sm={6}>
          <FormControl fullWidth>
            <InputLabel>Fee Model (Exchange)</InputLabel>
            <Select
              value={(feeExchanges?.exchanges?.length ?? 0) > 0 ? (paperSettings.fee_exchange || 'coinbase') : ''}
              label="Fee Model (Exchange)"
              onChange={(e) => {
                onSettingsChange({ ...paperSettings, fee_exchange: e.target.value })
              }}
            >
              {feeExchanges?.exchanges?.map((ex: any) => (
                <MenuItem key={ex.name} value={ex.name}>
                  {ex.name.charAt(0).toUpperCase() + ex.name.slice(1)} ({(ex.fees.taker * 100).toFixed(2)}% taker)
                </MenuItem>
              ))}
            </Select>
          </FormControl>
        </Grid>

        {/* Fee Rates Display */}
        <Grid item xs={12}>
          <Card variant="outlined" sx={{ bgcolor: 'action.hover' }}>
            <CardContent sx={{ py: 1.5 }}>
              <Typography variant="subtitle2" color="text.secondary" gutterBottom>
                Current Fee Rates
              </Typography>
              <Box sx={{ display: 'flex', gap: 4 }}>
                <Box>
                  <Typography variant="caption" color="text.secondary">Maker Fee</Typography>
                  <Typography variant="body1" fontWeight={600}>
                    {paperSettings.fee_rates ? (paperSettings.fee_rates.maker * 100).toFixed(2) : '0.10'}%
                  </Typography>
                </Box>
                <Box>
                  <Typography variant="caption" color="text.secondary">Taker Fee</Typography>
                  <Typography variant="body1" fontWeight={600}>
                    {paperSettings.fee_rates ? (paperSettings.fee_rates.taker * 100).toFixed(2) : '0.10'}%
                  </Typography>
                </Box>
                <Box>
                  <Typography variant="caption" color="text.secondary">Est. Round-Trip</Typography>
                  <Typography variant="body1" fontWeight={600} color="warning.main">
                    {paperSettings.fee_rates ? ((paperSettings.fee_rates.taker * 2) * 100).toFixed(2) : '0.20'}%
                  </Typography>
                </Box>
              </Box>
            </CardContent>
          </Card>
        </Grid>

        {/* Actions */}
        <Grid item xs={12}>
          <Box sx={{ display: 'flex', gap: 2 }}>
            <Button variant="contained" onClick={onSave} disabled={isPending}>
              Save Settings
            </Button>
            <Button
              variant="outlined"
              color="error"
              onClick={onReset}
              disabled={isResetting}
            >
              Reset Paper Account
            </Button>
          </Box>
        </Grid>
      </Grid>
    </Box>
  )
}

// Data Providers Settings Section
function DataProvidersSection() {
  const queryClient = useQueryClient()
  const { showSuccess, showError } = useSnackbar()
  const [showDetails, setShowDetails] = useState(false)

  const { data: config, isLoading: configLoading } = useQuery({
    queryKey: ['provider-config'],
    queryFn: marketDataApi.getProviderConfig,
  })

  const { data: status } = useQuery({
    queryKey: ['provider-status'],
    queryFn: marketDataApi.getProviderStatus,
    refetchInterval: 5000,
  })

  const updateConfigMutation = useMutation({
    mutationFn: marketDataApi.updateProviderConfig,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['provider-config'] })
      queryClient.invalidateQueries({ queryKey: ['provider-status'] })
      showSuccess('Provider configuration updated successfully')
    },
    onError: (error: any) => {
      showError(`Failed to update configuration: ${error.message}`)
    },
  })

  const handleToggleProvider = (providerName: string, enabled: boolean) => {
    if (!config) return

    const updatedConfig = { ...config }
    const providerIndex = updatedConfig.primary.findIndex((p: any) => p.name === providerName)

    if (providerIndex >= 0) {
      updatedConfig.primary[providerIndex] = {
        ...updatedConfig.primary[providerIndex],
        enabled,
      }
      updateConfigMutation.mutate(updatedConfig)
    }
  }

  const handleMoveProvider = (providerName: string, direction: 'up' | 'down') => {
    if (!config) return

    const updatedConfig = { ...config }
    const providerIndex = updatedConfig.primary.findIndex((p: any) => p.name === providerName)

    if (providerIndex < 0) return

    const newIndex = direction === 'up' ? providerIndex - 1 : providerIndex + 1

    if (newIndex >= 0 && newIndex < updatedConfig.primary.length) {
      const [moved] = updatedConfig.primary.splice(providerIndex, 1)
      updatedConfig.primary.splice(newIndex, 0, moved)

      // Update priorities
      updatedConfig.primary = updatedConfig.primary.map((p: any, idx: number) => ({
        ...p,
        priority: idx + 1,
      }))

      updateConfigMutation.mutate(updatedConfig)
    }
  }

  if (configLoading) {
    return <CircularProgress />
  }

  if (!config) {
    return <MuiAlert severity="error">Failed to load provider configuration</MuiAlert>
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography variant="h6">Data Provider Configuration</Typography>
        <Button
          variant="outlined"
          startIcon={showDetails ? <ExpandLess /> : <ExpandMore />}
          onClick={() => setShowDetails(!showDetails)}
        >
          {showDetails ? 'Hide Details' : 'Show Details'}
        </Button>
      </Box>

      <MuiAlert severity="info" sx={{ mb: 2 }}>
        Data providers are used to fetch real-time pricing data for paper trading, backtesting, and ML training.
        They work independently of exchange integrations and don't require API keys.
      </MuiAlert>

      {/* Provider Status Overview */}
      {status && (
        <Box sx={{ mb: 3 }}>
          <ProviderStatusDisplay compact={false} showDetails={showDetails} />
        </Box>
      )}

      {/* Primary Providers */}
      <Typography variant="subtitle1" gutterBottom sx={{ mt: 3, mb: 2 }}>
        Primary Providers (CCXT)
      </Typography>
      <TableContainer component={Paper} variant="outlined">
        <Table>
          <TableHead>
            <TableRow>
              <TableCell>Priority</TableCell>
              <TableCell>Provider</TableCell>
              <TableCell>Status</TableCell>
              <TableCell>Enabled</TableCell>
              <TableCell align="right">Actions</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {config.primary.map((provider: any, index: number) => {
              const providerStatus = status?.providers[provider.name] || status?.providers[`CCXT-${provider.name.charAt(0).toUpperCase() + provider.name.slice(1)}`]
              const healthStatus = providerStatus?.status || 'unknown'

              return (
                <TableRow key={provider.name}>
                  <TableCell>
                    <Chip label={provider.priority} size="small" />
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2" sx={{ fontWeight: 500 }}>
                      {provider.name.charAt(0).toUpperCase() + provider.name.slice(1)}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <StatusIndicator
                      status={
                        healthStatus === 'healthy'
                          ? 'connected'
                          : healthStatus === 'degraded'
                            ? 'warning'
                            : healthStatus === 'unhealthy'
                              ? 'error'
                              : 'unknown'
                      }
                      label={healthStatus}
                    />
                    {showDetails && providerStatus && (
                      <Typography variant="caption" display="block" color="text.secondary">
                        Avg: {providerStatus.avg_response_time?.toFixed(3)}s
                      </Typography>
                    )}
                  </TableCell>
                  <TableCell>
                    <Switch
                      checked={provider.enabled}
                      onChange={(e) => handleToggleProvider(provider.name, e.target.checked)}
                      size="small"
                    />
                  </TableCell>
                  <TableCell align="right">
                    <IconButton
                      size="small"
                      onClick={() => handleMoveProvider(provider.name, 'up')}
                      disabled={index === 0}
                    >
                      <ArrowUpward fontSize="small" />
                    </IconButton>
                    <IconButton
                      size="small"
                      onClick={() => handleMoveProvider(provider.name, 'down')}
                      disabled={index === config.primary.length - 1}
                    >
                      <ArrowDownward fontSize="small" />
                    </IconButton>
                  </TableCell>
                </TableRow>
              )
            })}
          </TableBody>
        </Table>
      </TableContainer>

      {/* Fallback Provider */}
      <Typography variant="subtitle1" gutterBottom sx={{ mt: 3, mb: 2 }}>
        Fallback Provider
      </Typography>
      <Card variant="outlined">
        <CardContent>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Box>
              <Typography variant="body1" sx={{ fontWeight: 500 }}>
                {config.fallback.name.charAt(0).toUpperCase() + config.fallback.name.slice(1)}
              </Typography>
              <Typography variant="caption" color="text.secondary">
                Used when primary providers are unavailable
              </Typography>
            </Box>
            <Switch
              checked={config.fallback.enabled}
              onChange={(e) => {
                const updatedConfig = {
                  ...config,
                  fallback: { ...config.fallback, enabled: e.target.checked },
                }
                updateConfigMutation.mutate(updatedConfig)
              }}
            />
          </Box>
        </CardContent>
      </Card>

      {/* Cache Configuration */}
      <Typography variant="subtitle1" gutterBottom sx={{ mt: 3, mb: 2 }}>
        Cache Configuration
      </Typography>
      <Grid container spacing={2} sx={{ maxWidth: 600 }}>
        <Grid item xs={12} sm={6}>
          <TextField
            fullWidth
            label="Ticker TTL (seconds)"
            type="number"
            value={config.caching.ticker_ttl}
            onChange={(e) => {
              const updatedConfig = {
                ...config,
                caching: {
                  ...config.caching,
                  ticker_ttl: parseInt(e.target.value) || 2,
                },
              }
              updateConfigMutation.mutate(updatedConfig)
            }}
            inputProps={{ min: 1, max: 60 }}
          />
        </Grid>
        <Grid item xs={12} sm={6}>
          <TextField
            fullWidth
            label="OHLCV TTL (seconds)"
            type="number"
            value={config.caching.ohlcv_ttl}
            onChange={(e) => {
              const updatedConfig = {
                ...config,
                caching: {
                  ...config.caching,
                  ohlcv_ttl: parseInt(e.target.value) || 60,
                },
              }
              updateConfigMutation.mutate(updatedConfig)
            }}
            inputProps={{ min: 1, max: 3600 }}
          />
        </Grid>
      </Grid>
    </Box>
  )
}

// Autopilot Settings Section
function AutopilotSettingsSection() {
  const queryClient = useQueryClient()
  const { showSuccess, showError, showWarning, showInfo } = useSnackbar()
  const settings = useAutopilotSettings()
  const updateSettings = useUpdateAutopilotSettings()

  const [trainingProgress, setTrainingProgress] = useState<{
    step: string
    progress: number
    total: number
    percent: number
    message: string
  } | null>(null)

  // Listen for training progress via WebSocket (using global context)
  const { subscribe } = useWebSocketContext()

  useEffect(() => {
    const unsubscribe = subscribe('training_progress', (data: any) => {
      setTrainingProgress({
        step: data.step,
        progress: data.progress,
        total: data.total,
        percent: data.percent,
        message: data.message,
      })
      // Clear progress after completion or error
      if (data.step === 'complete' || data.step === 'error') {
        setTimeout(() => setTrainingProgress(null), 5000)
      }
    })
    return unsubscribe
  }, [subscribe])




  // Model Info Query (for intelligent mode)
  const { data: modelInfo } = useQuery({
    queryKey: ['model-info'],
    queryFn: () => autopilotApi.getModelInfo(),
    refetchInterval: 30000,
    enabled: true,
  })

  // Bootstrap Config Query
  const { data: serverBootstrapConfig } = useQuery({
    queryKey: ['bootstrap-config'],
    queryFn: () => autopilotApi.getBootstrapConfig(),
    enabled: true,
  })

  // Local state for editing bootstrap config
  const [localBootstrapConfig, setLocalBootstrapConfig] = useState<{
    days: number
    timeframe: string
    min_samples_per_strategy: number
    symbols: string[]
  } | null>(null)

  // Sync local state when server data loads
  useEffect(() => {
    if (serverBootstrapConfig && !localBootstrapConfig) {
      setLocalBootstrapConfig(serverBootstrapConfig)
    }
  }, [serverBootstrapConfig, localBootstrapConfig])

  // Use local state if available, otherwise fall back to server data
  const bootstrapConfig = localBootstrapConfig || serverBootstrapConfig || {
    days: 90,
    timeframe: '1h',
    min_samples_per_strategy: 10,
    symbols: ['BTC/USD', 'ETH/USD']
  }

  const updateBootstrapMutation = useMutation({
    mutationFn: autopilotApi.updateBootstrapConfig,
    onSuccess: () => {
      setLocalBootstrapConfig(null) // Reset local state to allow re-sync with server
      queryClient.invalidateQueries({ queryKey: ['bootstrap-config'] })
      showSuccess('Bootstrap configuration saved')
    },
    onError: (error: any) => {
      showError(`Failed to save: ${error.message}`)
    },
  })

  // Track current training task (persist across navigation)
  const [currentTaskId, setCurrentTaskId] = useState<string | null>(() => {
    return localStorage.getItem('active_training_task_id')
  })
  const [pollingErrorCount, setPollingErrorCount] = useState(0)

  // Persist task ID changes
  useEffect(() => {
    if (currentTaskId) {
      localStorage.setItem('active_training_task_id', currentTaskId)
    } else {
      localStorage.removeItem('active_training_task_id')
      setPollingErrorCount(0)
    }
  }, [currentTaskId])

  // Poll for task status
  const { data: taskStatusData, error: taskStatusError } = useQuery({
    queryKey: ['task-status', currentTaskId],
    queryFn: () => autopilotApi.getTaskStatus(currentTaskId!),
    enabled: !!currentTaskId,
    refetchInterval: 1000, // Poll every second
    refetchIntervalInBackground: true,
  })

  // Effect to handle polling updates - react to taskStatusData changes
  useEffect(() => {
    if (!currentTaskId) return

    // Handle errors
    if (taskStatusError) {
      console.error("Polling error:", taskStatusError)
      setPollingErrorCount(prev => {
        const newCount = prev + 1
        if (newCount >= 3) {
          setCurrentTaskId(null)
          setTrainingProgress(null)
          showError("Lost connection to training task. Please check logs.")
        }
        return newCount
      })
      return
    }

    const data = taskStatusData
    if (!data) return

    // Reset error count on successful fetch
    setPollingErrorCount(0)

    if (!data) return

    // Reset error count on successful fetch
    setPollingErrorCount(0)

    // Update progress if available
    if (data.status === 'PROGRESS' && data.meta) {
      setTrainingProgress({
        step: data.meta.step,
        progress: data.meta.progress,
        total: 100, // Normalized to 100%
        percent: data.meta.progress,
        message: data.meta.message,
      })
    } else if (data.status === 'PENDING' || data.status === 'STARTED') {
      setTrainingProgress({
        step: 'pending',
        progress: 0,
        total: 100,
        percent: 0,
        message: 'Initializing training task...',
      })
    }

    // Handle completion
    if (data.status === 'SUCCESS') {
      setCurrentTaskId(null) // This triggers the useEffect to clear localStorage
      queryClient.invalidateQueries({ queryKey: ['model-info'] })

      const result = data.result || {}

      // Clear progress after short delay
      setTrainingProgress({
        step: 'complete',
        progress: 100,
        total: 100,
        percent: 100,
        message: 'Training completed successfully!'
      })
      setTimeout(() => setTrainingProgress(null), 5000)

      if (result.training_results) {
        const metrics = result.training_results.metrics || {}
        const accuracy = metrics.test_accuracy || metrics.test_rmse || 0
        const accuracyText = metrics.test_accuracy
          ? `Accuracy: ${(accuracy * 100).toFixed(1)}%`
          : metrics.test_rmse
            ? `RMSE: ${accuracy.toFixed(4)}`
            : ''
        showSuccess(`Model retrained successfully! ${accuracyText}`)
      } else {
        showSuccess('Model retrained successfully!')
      }
    } else if (data.status === 'FAILURE') {
      setCurrentTaskId(null)
      setTrainingProgress({
        step: 'error',
        progress: 100,
        total: 100,
        percent: 100,
        message: 'Training failed'
      })
      setTimeout(() => setTrainingProgress(null), 5000) // Keep error visible for a bit
      const errorMessage = data.result?.error || data.result?.detail || data.meta?.error || 'Unknown error'
      showError(`Training failed: ${errorMessage}`)
    }
  }, [currentTaskId, taskStatusData, taskStatusError, queryClient, showSuccess, showError])

  const retrainModelMutation = useMutation({
    mutationFn: autopilotApi.retrainModel,
    onSuccess: (data) => {
      // Just set the task ID to start polling
      if (data.task_id) {
        setCurrentTaskId(data.task_id)
        showInfo('Retraining started in background...')
      } else {
        // Fallback for immediate response (legacy)
        if (data.status === 'success') {
          showSuccess('Retraining complete')
        }
      }
    },
    onError: (error: any) => {
      const errorMessage = error?.response?.data?.detail || error?.message || 'Unknown error'
      showError(`Failed to start retraining: ${errorMessage}`)
    },
  })


  const resetModelMutation = useMutation({
    mutationFn: autopilotApi.resetModel,
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['model-info'] })
      showSuccess(data.message || 'Model reset successfully')
    },
    onError: (error: any) => {
      const errorMessage = error?.response?.data?.detail || error?.message || 'Unknown error'
      showError(`Failed to reset model: ${errorMessage}`)
    },
  })

  const handleAutoExecuteToggle = (checked: boolean) => {
    updateSettings({ autoExecute: checked })
    if (checked) {
      showWarning('Auto-execution enabled: Trades will be executed automatically!')
    }
  }

  const handleRetrainModel = () => {
    retrainModelMutation.mutate(true)
  }

  const handleResetModel = () => {
    if (window.confirm('Are you sure you want to reset the model? This will delete all saved model files.')) {
      resetModelMutation.mutate()
    }
  }

  return (
    <Box>
      <Typography variant="h6" gutterBottom>
        Autopilot Configuration
      </Typography>

      <Box sx={{ mb: 3 }}>
        <MuiAlert severity="info">
          Autopilot running in Intelligent (ML-Driven) Mode.
        </MuiAlert>
      </Box>

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

      {/* Auto-Execution Toggle */}
      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2 }}>
          Auto-Execution
        </Typography>
        <FormControlLabel
          control={
            <Switch
              checked={settings.autoExecute}
              onChange={(e) => handleAutoExecuteToggle(e.target.checked)}
              color="warning"
            />
          }
          label={
            <Box>
              <Typography variant="body1" sx={{ fontWeight: 500 }}>
                Enable Auto-Execution {settings.autoExecute && '⚠️'}
              </Typography>
              <Typography variant="body2" color="text.secondary">
                Automatically execute trades based on autopilot signals
              </Typography>
            </Box>
          }
        />
      </Box>

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

      {/* Pattern Mode Settings */}


      {/* Intelligent Mode Settings */}

      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2 }}>
          Intelligent Mode Settings
        </Typography>
        <Grid container spacing={2} sx={{ maxWidth: 600 }}>
          <Grid item xs={12} md={6}>
            <FormControl fullWidth>
              <InputLabel>Timeframe</InputLabel>
              <Select
                value={settings.timeframe}
                label="Timeframe"
                onChange={(e) => updateSettings({ timeframe: e.target.value })}
              >
                <MenuItem value="1m">1m</MenuItem>
                <MenuItem value="5m">5m</MenuItem>
                <MenuItem value="15m">15m</MenuItem>
                <MenuItem value="1h">1h</MenuItem>
                <MenuItem value="4h">4h</MenuItem>
                <MenuItem value="1d">1d</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="Exchange ID"
              type="number"
              value={settings.exchange_id}
              onChange={(e) => updateSettings({ exchange_id: parseInt(e.target.value) || 1 })}
              inputProps={{ step: 1, min: 1 }}
              helperText="ID of the exchange to use"
            />
          </Grid>
        </Grid>

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

        {/* Bootstrap Configuration */}
        <Box sx={{ mb: 3 }}>
          <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2 }}>
            Training Data Configuration
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 2 }}>
            Configure how much historical data to fetch when training the ML model.
          </Typography>
          {bootstrapConfig && (
            <Grid container spacing={2} sx={{ maxWidth: 600 }}>
              <Grid item xs={12} md={6}>
                <TextField
                  fullWidth
                  label="Historical Data (days)"
                  type="number"
                  value={bootstrapConfig.days}
                  onChange={(e) => {
                    setLocalBootstrapConfig({ ...bootstrapConfig, days: parseInt(e.target.value) || 90 })
                  }}
                  inputProps={{ step: 1, min: 7, max: 365 }}
                  helperText="Days of data to fetch (more = better training)"
                />
              </Grid>
              <Grid item xs={12} md={6}>
                <FormControl fullWidth>
                  <InputLabel>Timeframe</InputLabel>
                  <Select
                    value={bootstrapConfig.timeframe}
                    label="Timeframe"
                    onChange={(e) => {
                      setLocalBootstrapConfig({ ...bootstrapConfig, timeframe: e.target.value })
                    }}
                  >
                    <MenuItem value="1m">1m (most data)</MenuItem>
                    <MenuItem value="5m">5m</MenuItem>
                    <MenuItem value="15m">15m</MenuItem>
                    <MenuItem value="1h">1h (recommended)</MenuItem>
                    <MenuItem value="4h">4h</MenuItem>
                    <MenuItem value="1d">1d (least data)</MenuItem>
                  </Select>
                </FormControl>
              </Grid>
              <Grid item xs={12}>
                <TextField
                  fullWidth
                  label="Min Samples per Strategy"
                  type="number"
                  value={bootstrapConfig.min_samples_per_strategy}
                  onChange={(e) => {
                    setLocalBootstrapConfig({ ...bootstrapConfig, min_samples_per_strategy: parseInt(e.target.value) || 10 })
                  }}
                  inputProps={{ step: 1, min: 5, max: 100 }}
                  helperText="Minimum training samples required per strategy (30+ recommended)"
                />
              </Grid>
              <Grid item xs={12}>
                <Autocomplete
                  multiple
                  freeSolo
                  options={['BTC/USD', 'ETH/USD', 'SOL/USD', 'XRP/USD', 'ADA/USD', 'DOGE/USD', 'AVAX/USD', 'DOT/USD', 'LINK/USD', 'MATIC/USD']}
                  value={bootstrapConfig.symbols || []}
                  onChange={(_, newValue) => {
                    setLocalBootstrapConfig({ ...bootstrapConfig, symbols: newValue as string[] })
                  }}
                  renderTags={(value, getTagProps) =>
                    value.map((option, index) => (
                      <Chip
                        variant="outlined"
                        label={option}
                        size="small"
                        {...getTagProps({ index })}
                        key={option}
                      />
                    ))
                  }
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="Training Symbols"
                      helperText="Cryptocurrencies to use for ML training (type to add custom)"
                    />
                  )}
                />
              </Grid>
              <Grid item xs={12}>
                <Button
                  variant="outlined"
                  onClick={() => updateBootstrapMutation.mutate(bootstrapConfig)}
                  disabled={updateBootstrapMutation.isPending}
                >
                  Save Bootstrap Config
                </Button>
              </Grid>
            </Grid>
          )
          }
        </Box >

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

        {/* Model Management */}
        <Box>
          <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 2 }}>
            Model Management
          </Typography>
          <Card variant="outlined" sx={{ mb: 2 }}>
            <CardContent>
              {modelInfo?.is_trained ? (
                <Box>
                  <Chip
                    label="Global Model Trained"
                    color="success"
                    size="small"
                    sx={{ mb: 1, fontWeight: 600 }}
                  />
                  <Typography variant="body2" sx={{ mb: 0.5 }}>
                    Strategies: {modelInfo?.available_strategies?.length || 0}
                  </Typography>
                  <Typography variant="body2" sx={{ mb: 0.5 }}>
                    Features: {modelInfo?.feature_count || 0}
                  </Typography>
                  {modelInfo?.training_metadata && (
                    <>
                      <Typography variant="caption" color="text.secondary" display="block">
                        Accuracy: {(modelInfo.training_metadata.metrics?.test_accuracy * 100 || 0).toFixed(1)}%
                      </Typography>
                      <Typography variant="caption" color="text.secondary" display="block" sx={{ mt: 0.5 }}>
                        Trained on: {
                          modelInfo.training_metadata.training_symbols && modelInfo.training_metadata.training_symbols.length > 0
                            ? modelInfo.training_metadata.training_symbols.join(', ')
                            : 'Shared Data'
                        }
                      </Typography>
                    </>
                  )}
                </Box>
              ) : (
                <Typography variant="body2" color="text.secondary">
                  Model not trained. Using fallback selection.
                </Typography>
              )}
            </CardContent>
          </Card>

          {/* Training Progress Display */}
          {trainingProgress && (
            <Box sx={{ mb: 2 }}>
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 1 }}>
                <Typography variant="body2" sx={{ flexGrow: 1 }}>
                  {trainingProgress.message}
                </Typography>
                <Typography variant="caption" color="text.secondary">
                  {trainingProgress.progress}/{trainingProgress.total}
                </Typography>
              </Box>
              <LinearProgress
                variant="determinate"
                value={trainingProgress.percent}
                color={trainingProgress.step === 'error' ? 'error' : trainingProgress.step === 'complete' ? 'success' : 'primary'}
                sx={{ height: 8, borderRadius: 1 }}
              />
            </Box>
          )}
          <Box sx={{ display: 'flex', gap: 1 }}>
            <Button
              variant="outlined"
              startIcon={retrainModelMutation.isPending ? <CircularProgress size={16} /> : <Psychology />}
              onClick={handleRetrainModel}
              disabled={retrainModelMutation.isPending || resetModelMutation.isPending}
            >
              {retrainModelMutation.isPending ? 'Bootstrap & Training...' : 'Retrain Model'}
            </Button>
            <Button
              variant="outlined"
              color="error"
              onClick={handleResetModel}
              disabled={retrainModelMutation.isPending || resetModelMutation.isPending}
            >
              {resetModelMutation.isPending ? 'Resetting...' : 'Reset Model'}
            </Button>
          </Box>
          <Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
            Retrain the ML model with latest data, or reset to start fresh
          </Typography>
        </Box>

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


      </Box >

    </Box >
  )
}



function GeneralSettingsSection({ settings, onSave, isPending, onSettingsChange }: {
  settings?: GeneralSettings,
  onSave: () => void,
  isPending: boolean,
  onSettingsChange: (settings: GeneralSettings) => void
}) {
  const timezones = (Intl as any).supportedValuesOf ? (Intl as any).supportedValuesOf('timeZone') : ['UTC', 'America/New_York', 'Europe/London', 'Asia/Tokyo'];

  return (
    <Box sx={{ maxWidth: 600 }}>
      <Typography variant="h6" gutterBottom>
        General Settings
      </Typography>
      <MuiAlert severity="info" sx={{ mb: 3 }}>
        Configure your display preferences, including timezone and theme.
      </MuiAlert>

      {settings && (
        <Grid container spacing={3}>
          <Grid item xs={12}>
            <FormControl fullWidth>
              <InputLabel>Display Timezone</InputLabel>
              <Select
                value={settings.timezone}
                label="Display Timezone"
                onChange={(e) => onSettingsChange({ ...settings, timezone: e.target.value })}
              >
                <MenuItem value="UTC">UTC (Universal Time)</MenuItem>
                <MenuItem value="local">Browser Local Time</MenuItem>
                {timezones.map((tz: string) => (
                  <MenuItem key={tz} value={tz}>{tz}</MenuItem>
                ))}
              </Select>
            </FormControl>
            <Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: 'block' }}>
              Used to format all timestamps in the application.
            </Typography>
          </Grid>

          <Grid item xs={12}>
            <FormControl fullWidth>
              <InputLabel>Theme Preference</InputLabel>
              <Select
                value={settings.theme}
                label="Theme Preference"
                onChange={(e) => onSettingsChange({ ...settings, theme: e.target.value })}
              >
                <MenuItem value="dark">Dark Mode (Default)</MenuItem>
                <MenuItem value="light">Light Mode</MenuItem>
                <MenuItem value="system">System Preference</MenuItem>
              </Select>
            </FormControl>
          </Grid>

          <Grid item xs={12}>
            <FormControl fullWidth>
              <InputLabel>Display Currency</InputLabel>
              <Select
                value={settings.currency}
                label="Display Currency"
                onChange={(e) => onSettingsChange({ ...settings, currency: e.target.value })}
              >
                <MenuItem value="USD">USD ($)</MenuItem>
                <MenuItem value="EUR">EUR (€)</MenuItem>
                <MenuItem value="GBP">GBP (£)</MenuItem>
                <MenuItem value="BTC">BTC (₿)</MenuItem>
              </Select>
            </FormControl>
          </Grid>

          <Grid item xs={12}>
            <Button variant="contained" onClick={onSave} disabled={isPending}>
              Save General Settings
            </Button>
          </Grid>
        </Grid>
      )}
    </Box>
  )
}

function AlertsSection() {
  const queryClient = useQueryClient()
  const { showError } = useSnackbar()
  const [dialogOpen, setDialogOpen] = useState(false)
  const [editingAlert, setEditingAlert] = useState<AlertResponse | null>(null)
  const [formData, setFormData] = useState<AlertCreate>({
    name: '',
    alert_type: 'price',
    condition: {},
  })

  const { data: alerts, isLoading } = useQuery({
    queryKey: ['alerts'],
    queryFn: () => alertsApi.listAlerts(),
  })

  const createMutation = useMutation({
    mutationFn: alertsApi.createAlert,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['alerts'] })
      setDialogOpen(false)
      resetForm()
    },
  })

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: AlertUpdate }) =>
      alertsApi.updateAlert(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['alerts'] })
      setDialogOpen(false)
      resetForm()
    },
  })

  const deleteMutation = useMutation({
    mutationFn: alertsApi.deleteAlert,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['alerts'] })
    },
  })

  const toggleMutation = useMutation({
    mutationFn: ({ id, enabled }: { id: number; enabled: boolean }) =>
      alertsApi.updateAlert(id, { enabled }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['alerts'] })
    },
  })

  const resetForm = () => {
    setFormData({ name: '', alert_type: 'price', condition: {} })
    setEditingAlert(null)
  }

  const handleOpenDialog = (alertItem?: AlertResponse) => {
    if (alertItem) {
      setEditingAlert(alertItem)
      setFormData({
        name: alertItem.name,
        alert_type: alertItem.alert_type,
        condition: alertItem.condition || {},
      })
    } else {
      resetForm()
    }
    setDialogOpen(true)
  }

  const handleSave = () => {
    if (!formData.name) {
      showError('Name is required')
      return
    }
    if (editingAlert) {
      updateMutation.mutate({ id: editingAlert.id, data: { name: formData.name, condition: formData.condition } })
    } else {
      createMutation.mutate(formData)
    }
  }

  const handleDelete = (alertId: number) => {
    if (window.confirm('Are you sure you want to delete this alert?')) {
      deleteMutation.mutate(alertId)
    }
  }

  const handleToggle = (alertItem: AlertResponse) => {
    toggleMutation.mutate({ id: alertItem.id, enabled: !alertItem.enabled })
  }

  const getConditionDescription = (condition: Record<string, any>) => {
    if (!condition || Object.keys(condition).length === 0) return 'No condition set'
    const parts: string[] = []
    if (condition.symbol) parts.push(`Symbol: ${condition.symbol}`)
    if (condition.price_threshold) parts.push(`Price: $${condition.price_threshold}`)
    if (condition.percentage_change) parts.push(`Change: ${condition.percentage_change}%`)
    return parts.join(', ') || JSON.stringify(condition)
  }

  const getConditionFields = () => {
    const condition = formData.condition || {}
    if (formData.alert_type === 'price') {
      return (
        <>
          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="Symbol"
              value={condition.symbol || ''}
              onChange={(e) => setFormData((prev) => ({ ...prev, condition: { ...prev.condition, symbol: e.target.value } }))}
              placeholder="BTC/USD"
            />
          </Grid>
          <Grid item xs={12} md={6}>
            <FormControl fullWidth>
              <InputLabel>Condition</InputLabel>
              <Select
                value={condition.operator || 'above'}
                label="Condition"
                onChange={(e) => setFormData((prev) => ({ ...prev, condition: { ...prev.condition, operator: e.target.value } }))}
              >
                <MenuItem value="above">Price Above</MenuItem>
                <MenuItem value="below">Price Below</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12} md={6}>
            <TextField
              fullWidth
              label="Price Threshold"
              type="number"
              value={condition.price_threshold || ''}
              onChange={(e) => setFormData((prev) => ({ ...prev, condition: { ...prev.condition, price_threshold: parseFloat(e.target.value) || 0 } }))}
            />
          </Grid>
        </>
      )
    }
    return null
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
        <Typography variant="h6">Price & System Alerts</Typography>
        <Button variant="contained" startIcon={<Add />} onClick={() => handleOpenDialog()}>
          Create Alert
        </Button>
      </Box>

      <TableContainer>
        <Table size="small">
          <TableHead>
            <TableRow>
              <TableCell>Name</TableCell>
              <TableCell>Type</TableCell>
              <TableCell>Condition</TableCell>
              <TableCell>Status</TableCell>
              <TableCell align="right">Actions</TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {isLoading ? (
              <TableRow><TableCell colSpan={5} align="center">Loading...</TableCell></TableRow>
            ) : alerts && alerts.length > 0 ? (
              alerts.map((alertItem: AlertResponse) => (
                <TableRow key={alertItem.id}>
                  <TableCell>{alertItem.name}</TableCell>
                  <TableCell><Chip label={alertItem.alert_type} size="small" /></TableCell>
                  <TableCell>{getConditionDescription(alertItem.condition)}</TableCell>
                  <TableCell>
                    <Chip label={alertItem.enabled ? 'Enabled' : 'Disabled'} color={alertItem.enabled ? 'success' : 'default'} size="small" />
                  </TableCell>
                  <TableCell align="right">
                    <IconButton size="small" onClick={() => handleToggle(alertItem)}>
                      {alertItem.enabled ? <NotificationsActive /> : <NotificationsOff />}
                    </IconButton>
                    <IconButton size="small" onClick={() => handleOpenDialog(alertItem)}><Edit /></IconButton>
                    <IconButton size="small" color="error" onClick={() => handleDelete(alertItem.id)}><Delete /></IconButton>
                  </TableCell>
                </TableRow>
              ))
            ) : (
              <TableRow><TableCell colSpan={5} align="center">No alerts configured</TableCell></TableRow>
            )}
          </TableBody>
        </Table>
      </TableContainer>

      <Dialog open={dialogOpen} onClose={() => setDialogOpen(false)} maxWidth="md" fullWidth>
        <DialogTitle>{editingAlert ? 'Edit Alert' : 'Create Alert'}</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid item xs={12}>
              <TextField fullWidth label="Alert Name" value={formData.name} onChange={(e) => setFormData((prev) => ({ ...prev, name: e.target.value }))} required />
            </Grid>
            <Grid item xs={12} md={6}>
              <FormControl fullWidth required>
                <InputLabel>Alert Type</InputLabel>
                <Select
                  value={formData.alert_type}
                  label="Alert Type"
                  onChange={(e) => setFormData((prev) => ({ ...prev, alert_type: e.target.value, condition: {} }))}
                  disabled={!!editingAlert}
                >
                  <MenuItem value="price">Price Alert</MenuItem>
                  <MenuItem value="indicator">Indicator Alert</MenuItem>
                  <MenuItem value="risk">Risk Alert</MenuItem>
                  <MenuItem value="system">System Alert</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            {getConditionFields()}
            {(createMutation.isError || updateMutation.isError) && (
              <Grid item xs={12}>
                <MuiAlert severity="error">Failed to save alert</MuiAlert>
              </Grid>
            )}
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDialogOpen(false)}>Cancel</Button>
          <Button variant="contained" onClick={handleSave} disabled={createMutation.isPending || updateMutation.isPending}>
            Save
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  )
}

function ExchangeDialog({ open, onClose, exchange, onSave }: any) {
  const [formData, setFormData] = useState<ExchangeCreate>({
    name: exchange?.name || '',
    api_key: '',
    api_secret: '',
    sandbox: false,
    read_only: true,
    enabled: true,
  })

  const createMutation = useMutation({
    mutationFn: settingsApi.createExchange,
    onSuccess: onSave,
  })

  const updateMutation = useMutation({
    mutationFn: (data: ExchangeCreate) => settingsApi.updateExchange(exchange.id, data),
    onSuccess: onSave,
  })

  const handleSubmit = () => {
    if (exchange) {
      updateMutation.mutate(formData)
    } else {
      createMutation.mutate(formData)
    }
  }

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>{exchange ? 'Edit Exchange' : 'Add Exchange'}</DialogTitle>
      <DialogContent>
        <Grid container spacing={2} sx={{ mt: 1 }}>
          <Grid item xs={12}>
            <TextField fullWidth label="Exchange Name" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value })} disabled={!!exchange} required />
          </Grid>
          <Grid item xs={12}>
            <TextField fullWidth label="API Key" type="password" value={formData.api_key} onChange={(e) => setFormData({ ...formData, api_key: e.target.value })} />
          </Grid>
          <Grid item xs={12}>
            <TextField fullWidth label="API Secret" type="password" value={formData.api_secret} onChange={(e) => setFormData({ ...formData, api_secret: e.target.value })} />
          </Grid>
          <Grid item xs={12}>
            <FormControlLabel control={<Checkbox checked={formData.sandbox} onChange={(e) => setFormData({ ...formData, sandbox: e.target.checked })} />} label="Use Sandbox/Testnet" />
          </Grid>
          <Grid item xs={12}>
            <FormControlLabel control={<Checkbox checked={formData.read_only} onChange={(e) => setFormData({ ...formData, read_only: e.target.checked })} />} label="Read-Only Mode" />
          </Grid>
          <Grid item xs={12}>
            <FormControlLabel control={<Checkbox checked={formData.enabled} onChange={(e) => setFormData({ ...formData, enabled: e.target.checked })} />} label="Enabled" />
          </Grid>
        </Grid>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancel</Button>
        <Button variant="contained" onClick={handleSubmit} disabled={createMutation.isPending || updateMutation.isPending}>Save</Button>
      </DialogActions>
    </Dialog>
  )
}
