import { useState, useEffect } from 'react'
import { useMutation } from '@tanstack/react-query'
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Grid,
  Alert,
  Switch,
  FormControlLabel,
  Box,
  Typography,
  Tabs,
  Tab,
} from '@mui/material'
import { strategiesApi } from '../api/strategies'
import { StrategyResponse, StrategyCreate, StrategyUpdate } from '../types'
import StrategyParameterForm from './StrategyParameterForm'
import { useSnackbar } from '../contexts/SnackbarContext'

interface StrategyDialogProps {
  open: boolean
  onClose: () => void
  strategy: StrategyResponse | null
  exchanges: Array<{ id: number; name: string }>
  onSave: () => void
}

const STRATEGY_TYPES = [
  { value: 'rsi', label: 'RSI Strategy' },
  { value: 'macd', label: 'MACD Strategy' },
  { value: 'moving_average', label: 'Moving Average Crossover' },
  { value: 'confirmed', label: 'Confirmed Strategy (Multi-Indicator)' },
  { value: 'divergence', label: 'Divergence Strategy' },
  { value: 'bollinger_mean_reversion', label: 'Bollinger Bands Mean Reversion' },
  { value: 'consensus', label: 'Consensus Strategy (Ensemble)' },
  { value: 'dca', label: 'Dollar Cost Averaging' },
  { value: 'grid', label: 'Grid Trading' },
  { value: 'momentum', label: 'Momentum Strategy' },
  { value: 'pairs_trading', label: 'Statistical Arbitrage (Pairs)' },
  { value: 'volatility_breakout', label: 'Volatility Breakout' },
  { value: 'sentiment', label: 'Sentiment / News Trading' },
  { value: 'market_making', label: 'Market Making' },
]

const TIMEFRAMES = ['1m', '5m', '15m', '30m', '1h', '4h', '1d']

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',
]

export default function StrategyDialog({
  open,
  onClose,
  strategy,
  exchanges,
  onSave,
}: StrategyDialogProps) {
  const { showError } = useSnackbar()
  const [tabValue, setTabValue] = useState(0)
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [strategyType, setStrategyType] = useState('rsi')
  const [symbol, setSymbol] = useState('BTC/USD')
  const [exchangeId, setExchangeId] = useState<number | ''>('')
  const [timeframes, setTimeframes] = useState<string[]>(['1h'])
  const [paperTrading, setPaperTrading] = useState(true)
  const [enabled, setEnabled] = useState(false)
  const [parameters, setParameters] = useState<Record<string, any>>({})

  useEffect(() => {
    if (strategy) {
      setName(strategy.name)
      setDescription(strategy.description || '')
      setStrategyType(strategy.strategy_type)
      setSymbol(strategy.parameters?.symbol || 'BTC/USD')
      setExchangeId(strategy.parameters?.exchange_id || '')
      setTimeframes(strategy.timeframes || ['1h'])
      setPaperTrading(strategy.paper_trading)
      setEnabled(strategy.enabled)
      // Extract strategy-specific parameters (exclude symbol, exchange_id)
      const { symbol: _, exchange_id: __, ...strategyParams } = strategy.parameters || {}
      setParameters(strategyParams)
    } else {
      // Reset form
      setName('')
      setDescription('')
      setStrategyType('rsi')
      setSymbol('BTC/USD')
      setExchangeId('')
      setTimeframes(['1h'])
      setPaperTrading(true)
      setEnabled(false)
      setParameters({})
    }
  }, [strategy, open])

  const createMutation = useMutation({
    mutationFn: (data: StrategyCreate) => strategiesApi.createStrategy(data),
    onSuccess: onSave,
  })

  const updateMutation = useMutation({
    mutationFn: (data: StrategyUpdate) =>
      strategiesApi.updateStrategy(strategy!.id, data),
    onSuccess: onSave,
  })

  const handleSave = () => {
    if (!name.trim()) {
      showError('Strategy name is required')
      return
    }

    if (!exchangeId) {
      showError('Please select an exchange')
      return
    }

    const strategyData: StrategyCreate | StrategyUpdate = {
      name: name.trim(),
      description: description.trim() || undefined,
      strategy_type: strategyType,
      class_name: strategyType,
      parameters: {
        ...parameters,
        symbol,
        exchange_id: exchangeId,
      },
      timeframes,
      paper_trading: paperTrading,
      enabled: strategy ? enabled : false, // New strategies start disabled
    }

    if (strategy) {
      updateMutation.mutate(strategyData as StrategyUpdate)
    } else {
      createMutation.mutate(strategyData as StrategyCreate)
    }
  }

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>
        {strategy ? 'Edit Strategy' : 'Create Strategy'}
      </DialogTitle>
      <DialogContent>
        <Tabs value={tabValue} onChange={(_, v) => setTabValue(v)} sx={{ mb: 3 }}>
          <Tab label="Basic Settings" />
          <Tab label="Parameters" />
          <Tab label="Risk Settings" />
        </Tabs>

        {tabValue === 0 && (
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Strategy Name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                required
                helperText="A descriptive name for this strategy"
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Description"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                multiline
                rows={2}
                helperText="Optional description of the strategy"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <FormControl fullWidth required>
                <InputLabel>Strategy Type</InputLabel>
                <Select
                  value={strategyType}
                  label="Strategy Type"
                  onChange={(e) => {
                    setStrategyType(e.target.value)
                    setParameters({}) // Reset parameters when type changes
                  }}
                  disabled={!!strategy}
                >
                  {STRATEGY_TYPES.map((type) => (
                    <MenuItem key={type.value} value={type.value}>
                      {type.label}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={6}>
              <FormControl fullWidth required>
                <InputLabel>Symbol</InputLabel>
                <Select
                  value={symbol}
                  label="Symbol"
                  onChange={(e) => setSymbol(e.target.value)}
                >
                  {CRYPTO_PAIRS.map((pair) => (
                    <MenuItem key={pair} value={pair}>
                      {pair}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={6}>
              <FormControl fullWidth required>
                <InputLabel>Exchange</InputLabel>
                <Select
                  value={exchangeId}
                  label="Exchange"
                  onChange={(e) => setExchangeId(e.target.value as number)}
                >
                  {exchanges.map((ex) => (
                    <MenuItem key={ex.id} value={ex.id}>
                      {ex.name}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12} md={6}>
              <FormControl fullWidth>
                <InputLabel>Timeframes</InputLabel>
                <Select
                  multiple
                  value={timeframes}
                  label="Timeframes"
                  onChange={(e) => setTimeframes(e.target.value as string[])}
                  renderValue={(selected) => (selected as string[]).join(', ')}
                >
                  {TIMEFRAMES.map((tf) => (
                    <MenuItem key={tf} value={tf}>
                      {tf}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12}>
              <FormControlLabel
                control={
                  <Switch
                    checked={paperTrading}
                    onChange={(e) => setPaperTrading(e.target.checked)}
                  />
                }
                label="Paper Trading Mode"
              />
              <Typography variant="caption" display="block" color="text.secondary">
                Paper trading uses virtual funds for testing
              </Typography>
            </Grid>
            {strategy && (
              <Grid item xs={12}>
                <FormControlLabel
                  control={
                    <Switch
                      checked={enabled}
                      onChange={(e) => setEnabled(e.target.checked)}
                    />
                  }
                  label="Enable for Autopilot"
                />
                <Typography variant="caption" display="block" color="text.secondary">
                  Make this strategy available for ML-based selection
                </Typography>
              </Grid>
            )}
          </Grid>
        )}

        {tabValue === 1 && (
          <Box sx={{ mt: 2 }}>
            <StrategyParameterForm
              strategyType={strategyType}
              parameters={parameters}
              onChange={setParameters}
            />
          </Box>
        )}

        {tabValue === 2 && (
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="Position Size (%)"
                type="number"
                value={parameters.position_size_percent || 10}
                onChange={(e) =>
                  setParameters({
                    ...parameters,
                    position_size_percent: parseFloat(e.target.value) || 10,
                  })
                }
                inputProps={{ min: 0.1, max: 100, step: 0.1 }}
                helperText="Percentage of capital to use per trade"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="Stop Loss (%)"
                type="number"
                value={parameters.stop_loss_percent || 5}
                onChange={(e) =>
                  setParameters({
                    ...parameters,
                    stop_loss_percent: parseFloat(e.target.value) || 5,
                  })
                }
                inputProps={{ min: 0.1, max: 50, step: 0.1 }}
                helperText="Maximum loss percentage before exit"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="Take Profit (%)"
                type="number"
                value={parameters.take_profit_percent || 10}
                onChange={(e) =>
                  setParameters({
                    ...parameters,
                    take_profit_percent: parseFloat(e.target.value) || 10,
                  })
                }
                inputProps={{ min: 0.1, max: 100, step: 0.1 }}
                helperText="Profit target percentage"
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="Max Position Size"
                type="number"
                value={parameters.max_position_size || ''}
                onChange={(e) =>
                  setParameters({
                    ...parameters,
                    max_position_size: e.target.value ? parseFloat(e.target.value) : undefined,
                  })
                }
                inputProps={{ min: 0, step: 0.01 }}
                helperText="Maximum position size (optional)"
              />
            </Grid>
          </Grid>
        )}

        {(createMutation.isError || updateMutation.isError) && (
          <Alert severity="error" sx={{ mt: 2 }}>
            {createMutation.error instanceof Error
              ? createMutation.error.message
              : updateMutation.error instanceof Error
                ? updateMutation.error.message
                : 'Failed to save strategy'}
          </Alert>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancel</Button>
        <Button
          variant="contained"
          onClick={handleSave}
          disabled={createMutation.isPending || updateMutation.isPending}
        >
          {createMutation.isPending || updateMutation.isPending
            ? 'Saving...'
            : strategy
              ? 'Update'
              : 'Create'}
        </Button>
      </DialogActions>
    </Dialog>
  )
}

