import { useState, useEffect } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Grid,
  Alert,
  Box,
  Typography,
  Divider,
  Collapse,
} from '@mui/material'
import { ExpandMore, ExpandLess } from '@mui/icons-material'
import { tradingApi } from '../api/trading'
import { OrderCreate, OrderSide, OrderType } from '../types'
import { useSnackbar } from '../contexts/SnackbarContext'
import RealtimePrice from './RealtimePrice'
import ProviderStatusDisplay from './ProviderStatus'

interface OrderFormProps {
  open: boolean
  onClose: () => void
  exchanges: Array<{ id: number; name: string }>
  paperTrading: boolean
  onSuccess: () => void
}

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

const ORDER_TYPES = [
  { value: OrderType.MARKET, label: 'Market' },
  { value: OrderType.LIMIT, label: 'Limit' },
  { value: OrderType.STOP_LOSS, label: 'Stop Loss' },
  { value: OrderType.TAKE_PROFIT, label: 'Take Profit' },
  { value: OrderType.TRAILING_STOP, label: 'Trailing Stop' },
  { value: OrderType.OCO, label: 'OCO (One-Cancels-Other)' },
  { value: OrderType.ICEBERG, label: 'Iceberg' },
]

export default function OrderForm({
  open,
  onClose,
  exchanges,
  paperTrading,
  onSuccess,
}: OrderFormProps) {
  const queryClient = useQueryClient()
  const { showError } = useSnackbar()
  const [exchangeId, setExchangeId] = useState<number | ''>('')
  const [symbol, setSymbol] = useState('BTC/USD')
  const [side, setSide] = useState<OrderSide>(OrderSide.BUY)
  const [orderType, setOrderType] = useState<OrderType>(OrderType.MARKET)
  const [quantity, setQuantity] = useState('')
  const [price, setPrice] = useState('')
  const [stopPrice, setStopPrice] = useState('')
  const [showAdvanced, setShowAdvanced] = useState(false)

  useEffect(() => {
    if (exchanges.length > 0 && !exchangeId) {
      setExchangeId(exchanges[0].id)
    }
  }, [exchanges, exchangeId])

  useEffect(() => {
    if (!open) {
      // Reset form when dialog closes
      setExchangeId(exchanges.length > 0 ? exchanges[0].id : '')
      setSymbol('BTC/USD')
      setSide(OrderSide.BUY)
      setOrderType(OrderType.MARKET)
      setQuantity('')
      setPrice('')
      setStopPrice('')
      setShowAdvanced(false)
    }
  }, [open, exchanges])

  const createOrderMutation = useMutation({
    mutationFn: (order: OrderCreate) => tradingApi.createOrder(order),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['orders'] })
      queryClient.invalidateQueries({ queryKey: ['positions'] })
      queryClient.invalidateQueries({ queryKey: ['balance'] })
      onSuccess()
    },
  })

  const handleSubmit = () => {
    if (!exchangeId) {
      showError('Please select an exchange')
      return
    }

    if (!quantity || parseFloat(quantity) <= 0) {
      showError('Please enter a valid quantity')
      return
    }

    const requiresPrice = [
      OrderType.LIMIT,
      OrderType.STOP_LOSS,
      OrderType.TAKE_PROFIT,
    ].includes(orderType)

    if (requiresPrice && (!price || parseFloat(price) <= 0)) {
      showError('Please enter a valid price for this order type')
      return
    }

    const order: OrderCreate = {
      exchange_id: exchangeId as number,
      symbol,
      side,
      order_type: orderType,
      quantity: parseFloat(quantity),
      price: requiresPrice ? parseFloat(price) : undefined,
      paper_trading: paperTrading,
    }

    createOrderMutation.mutate(order)
  }

  const requiresPrice = [
    OrderType.LIMIT,
    OrderType.STOP_LOSS,
    OrderType.TAKE_PROFIT,
  ].includes(orderType)

  const requiresStopPrice = [
    OrderType.STOP_LOSS,
    OrderType.TRAILING_STOP,
  ].includes(orderType)

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>Place Order</DialogTitle>
      <DialogContent>
        <Grid container spacing={2} sx={{ mt: 1 }}>
          <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 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}>
            <Box sx={{ mb: 1 }}>
              <RealtimePrice symbol={symbol} size="small" showProvider={false} showChange={true} />
            </Box>
            <Divider sx={{ my: 1 }} />
          </Grid>
          <Grid item xs={12} md={6}>
            <FormControl fullWidth required>
              <InputLabel>Side</InputLabel>
              <Select
                value={side}
                label="Side"
                onChange={(e) => setSide(e.target.value as OrderSide)}
              >
                <MenuItem value={OrderSide.BUY}>Buy</MenuItem>
                <MenuItem value={OrderSide.SELL}>Sell</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12} md={6}>
            <FormControl fullWidth required>
              <InputLabel>Order Type</InputLabel>
              <Select
                value={orderType}
                label="Order Type"
                onChange={(e) => setOrderType(e.target.value as OrderType)}
              >
                {ORDER_TYPES.map((type) => (
                  <MenuItem key={type.value} value={type.value}>
                    {type.label}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12}>
            <TextField
              fullWidth
              label="Quantity"
              type="number"
              value={quantity}
              onChange={(e) => setQuantity(e.target.value)}
              required
              inputProps={{ min: 0, step: 0.00000001 }}
              helperText="Amount to buy or sell"
            />
          </Grid>
          {requiresPrice && (
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Price"
                type="number"
                value={price}
                onChange={(e) => setPrice(e.target.value)}
                required
                inputProps={{ min: 0, step: 0.01 }}
                helperText="Limit price for the order"
              />
            </Grid>
          )}
          {requiresStopPrice && (
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Stop Price"
                type="number"
                value={stopPrice}
                onChange={(e) => setStopPrice(e.target.value)}
                inputProps={{ min: 0, step: 0.01 }}
                helperText="Stop price for stop-loss or trailing stop orders"
              />
            </Grid>
          )}
          <Grid item xs={12}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
              <Button
                size="small"
                onClick={() => setShowAdvanced(!showAdvanced)}
                endIcon={showAdvanced ? <ExpandLess /> : <ExpandMore />}
              >
                Advanced Options
              </Button>
            </Box>
            <Collapse in={showAdvanced}>
              <Box sx={{ mt: 2, p: 2, bgcolor: 'background.default', borderRadius: 1 }}>
                <Typography variant="body2" color="text.secondary" gutterBottom>
                  Advanced order types (OCO, Iceberg) require additional configuration.
                  These features are available in the API but may need custom implementation.
                </Typography>
              </Box>
            </Collapse>
          </Grid>
          {paperTrading && (
            <Grid item xs={12}>
              <Alert severity="info">
                This order will be executed in paper trading mode with virtual funds.
              </Alert>
            </Grid>
          )}
          {createOrderMutation.isError && (
            <Grid item xs={12}>
              <Alert severity="error">
                {createOrderMutation.error instanceof Error
                  ? createOrderMutation.error.message
                  : 'Failed to place order'}
              </Alert>
            </Grid>
          )}
        </Grid>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Cancel</Button>
        <Button
          variant="contained"
          onClick={handleSubmit}
          disabled={createOrderMutation.isPending}
        >
          {createOrderMutation.isPending ? 'Placing...' : 'Place Order'}
        </Button>
      </DialogActions>
    </Dialog>
  )
}

