import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import {
  Card,
  CardContent,
  Typography,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Box,
  Grid,
  Chip,
  Alert,
  Divider,
} from '@mui/material'
import { Close } from '@mui/icons-material'
import { tradingApi } from '../api/trading'
import { PositionResponse, OrderCreate, OrderSide, OrderType } from '../types'
import { useSnackbar } from '../contexts/SnackbarContext'

interface PositionCardProps {
  position: PositionResponse
  paperTrading: boolean
  onClose: () => void
}

export default function PositionCard({
  position,
  paperTrading,
  onClose,
}: PositionCardProps) {
  const queryClient = useQueryClient()
  const { showError } = useSnackbar()
  const [closeDialogOpen, setCloseDialogOpen] = useState(false)
  const [closeType, setCloseType] = useState<OrderType>(OrderType.MARKET)
  const [closePrice, setClosePrice] = useState('')

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

  const handleClosePosition = () => {
    setCloseDialogOpen(true)
  }

  const handleConfirmClose = () => {
    // Extract exchange_id from position or use default
    // In a real implementation, you'd get this from the position or context
    const exchangeId = 1 // This should come from position data or context

    const requiresPrice = closeType === OrderType.LIMIT

    if (requiresPrice && (!closePrice || parseFloat(closePrice) <= 0)) {
      showError('Please enter a valid price for limit orders')
      return
    }

    const order: OrderCreate = {
      exchange_id: exchangeId,
      symbol: position.symbol,
      side: OrderSide.SELL,
      order_type: closeType,
      quantity: position.quantity,
      price: requiresPrice ? parseFloat(closePrice) : undefined,
      paper_trading: paperTrading,
    }

    closePositionMutation.mutate(order)
  }

  const pnlPercent =
    position.entry_price > 0
      ? ((position.current_price - position.entry_price) / position.entry_price) * 100
      : 0

  return (
    <>
      <Card>
        <CardContent>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', mb: 2 }}>
            <Typography variant="h6">{position.symbol}</Typography>
            <Chip
              label={pnlPercent >= 0 ? `+${pnlPercent.toFixed(2)}%` : `${pnlPercent.toFixed(2)}%`}
              color={pnlPercent >= 0 ? 'success' : 'error'}
              size="small"
            />
          </Box>
          <Grid container spacing={2}>
            <Grid item xs={6}>
              <Typography variant="caption" color="text.secondary">
                Quantity
              </Typography>
              <Typography variant="body1" sx={{ fontWeight: 500 }}>
                {Number(position.quantity).toFixed(8)}
              </Typography>
            </Grid>
            <Grid item xs={6}>
              <Typography variant="caption" color="text.secondary">
                Entry Price
              </Typography>
              <Typography variant="body1" sx={{ fontWeight: 500 }}>
                ${Number(position.entry_price).toFixed(2)}
              </Typography>
            </Grid>
            <Grid item xs={6}>
              <Typography variant="caption" color="text.secondary">
                Current Price
              </Typography>
              <Typography variant="body1" sx={{ fontWeight: 500 }}>
                ${Number(position.current_price).toFixed(2)}
              </Typography>
            </Grid>
            <Grid item xs={6}>
              <Typography variant="caption" color="text.secondary">
                Value
              </Typography>
              <Typography variant="body1" sx={{ fontWeight: 500 }}>
                ${(Number(position.quantity) * Number(position.current_price)).toFixed(2)}
              </Typography>
            </Grid>
            <Grid item xs={12}>
              <Divider sx={{ my: 1 }} />
            </Grid>
            <Grid item xs={6}>
              <Typography variant="caption" color="text.secondary">
                Unrealized P&L
              </Typography>
              <Typography
                variant="h6"
                sx={{
                  fontWeight: 'bold',
                  color: position.unrealized_pnl >= 0 ? 'success.main' : 'error.main',
                }}
              >
                {position.unrealized_pnl >= 0 ? '+' : ''}
                ${Number(position.unrealized_pnl).toFixed(2)}
              </Typography>
            </Grid>
            <Grid item xs={6}>
              <Typography variant="caption" color="text.secondary">
                Realized P&L
              </Typography>
              <Typography
                variant="body1"
                sx={{
                  fontWeight: 500,
                  color: position.realized_pnl >= 0 ? 'success.main' : 'error.main',
                }}
              >
                {position.realized_pnl >= 0 ? '+' : ''}
                ${Number(position.realized_pnl).toFixed(2)}
              </Typography>
            </Grid>
            <Grid item xs={12}>
              <Button
                variant="outlined"
                color="error"
                fullWidth
                startIcon={<Close />}
                onClick={handleClosePosition}
                sx={{ mt: 1 }}
              >
                Close Position
              </Button>
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      <Dialog open={closeDialogOpen} onClose={() => setCloseDialogOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle>Close Position</DialogTitle>
        <DialogContent>
          <Box sx={{ mt: 2 }}>
            <Alert severity="info" sx={{ mb: 2 }}>
              Closing {Number(position.quantity).toFixed(8)} {position.symbol} at current price of ${Number(position.current_price).toFixed(2)}
            </Alert>
            <FormControl fullWidth sx={{ mb: 2 }}>
              <InputLabel>Order Type</InputLabel>
              <Select
                value={closeType}
                label="Order Type"
                onChange={(e) => {
                  setCloseType(e.target.value as OrderType)
                  setClosePrice('')
                }}
              >
                <MenuItem value={OrderType.MARKET}>Market</MenuItem>
                <MenuItem value={OrderType.LIMIT}>Limit</MenuItem>
              </Select>
            </FormControl>
            {closeType === OrderType.LIMIT && (
              <TextField
                fullWidth
                label="Limit Price"
                type="number"
                value={closePrice}
                onChange={(e) => setClosePrice(e.target.value)}
                inputProps={{ min: 0, step: 0.01 }}
                helperText="Price at which to close the position"
              />
            )}
            {closePositionMutation.isError && (
              <Alert severity="error" sx={{ mt: 2 }}>
                {closePositionMutation.error instanceof Error
                  ? closePositionMutation.error.message
                  : 'Failed to close position'}
              </Alert>
            )}
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setCloseDialogOpen(false)}>Cancel</Button>
          <Button
            variant="contained"
            color="error"
            onClick={handleConfirmClose}
            disabled={closePositionMutation.isPending}
          >
            {closePositionMutation.isPending ? 'Closing...' : 'Close Position'}
          </Button>
        </DialogActions>
      </Dialog>
    </>
  )
}

