import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  Box,
  Paper,
  Typography,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Chip,
  IconButton,
  CircularProgress,
  Tooltip,
  Tabs,
  Tab,
  Card,
  CardContent,
  Grid,
  Switch,
  FormControlLabel,
} from '@mui/material'
import {
  Add,
  Cancel,
  TrendingUp,
  TrendingDown,
} from '@mui/icons-material'
import { tradingApi } from '../api/trading'
import { exchangesApi } from '../api/exchanges'
import { OrderResponse, PositionResponse, OrderSide, OrderStatus } from '../types'
import OrderForm from '../components/OrderForm'
import PositionCard from '../components/PositionCard'
import { settingsApi } from '../api/settings'
import { formatDate } from '../utils/formatters'
import {
  Checkbox,
  TextField,
  InputAdornment,
  ButtonGroup,
  Divider,
} from '@mui/material'
import {
  Search,
  DeleteSweep,
  ClearAll,
} from '@mui/icons-material'
import { useSnackbar } from '../contexts/SnackbarContext'

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={{ pt: 3 }}>{children}</Box>}
    </div>
  )
}

export default function TradingPage() {
  const { showSuccess, showError } = useSnackbar()
  const queryClient = useQueryClient()
  const [tabValue, setTabValue] = useState(0)
  const [orderDialogOpen, setOrderDialogOpen] = useState(false)
  const [paperTrading, setPaperTrading] = useState(true)

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

  const [selectedOrders, setSelectedOrders] = useState<number[]>([])
  const [symbolFilter, setSymbolFilter] = useState('')

  const { data: orders, isLoading: ordersLoading } = useQuery({
    queryKey: ['orders', paperTrading],
    queryFn: () => tradingApi.getOrders(paperTrading, 100),
    refetchInterval: 5000,
  })

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

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

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

  // Create order mutation moved to OrderForm or removed if redundant

  const cancelOrderMutation = useMutation({
    mutationFn: (orderId: number) => tradingApi.cancelOrder(orderId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['orders'] })
      showSuccess?.('Order cancelled successfully')
    },
    onError: (error: any) => {
      showError?.(`Failed to cancel order: ${error.message}`)
    }
  })

  const cancelAllOrdersMutation = useMutation({
    mutationFn: (paperTrading: boolean) => tradingApi.cancelAllOrders(paperTrading),
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['orders'] })
      showSuccess?.(`Cancelled ${data.cancelled_count} orders`)
    },
    onError: (error: any) => {
      showError?.(`Failed to cancel all orders: ${error.message}`)
    }
  })

  const cancelMultipleOrdersMutation = useMutation({
    mutationFn: async (orderIds: number[]) => {
      const results = await Promise.all(orderIds.map(id => tradingApi.cancelOrder(id)))
      return results
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['orders'] })
      setSelectedOrders([])
      showSuccess?.('Selected orders cancelled')
    },
    onError: (error: any) => {
      showError?.(`Failed to cancel selected orders: ${error.message}`)
    }
  })

  const handleCreateOrder = () => {
    setOrderDialogOpen(true)
  }

  const handleCancelOrder = (orderId: number) => {
    if (window.confirm('Are you sure you want to cancel this order?')) {
      cancelOrderMutation.mutate(orderId)
    }
  }

  const handleCancelAll = () => {
    if (window.confirm(`Are you sure you want to cancel ALL open ${paperTrading ? 'paper' : 'live'} orders?`)) {
      cancelAllOrdersMutation.mutate(paperTrading)
    }
  }

  const handleCancelSelected = () => {
    if (selectedOrders.length === 0) return
    if (window.confirm(`Are you sure you want to cancel ${selectedOrders.length} selected orders?`)) {
      cancelMultipleOrdersMutation.mutate(selectedOrders)
    }
  }

  const handleSelectOrder = (orderId: number) => {
    setSelectedOrders(prev =>
      prev.includes(orderId) ? prev.filter(id => id !== orderId) : [...prev, orderId]
    )
  }

  const handleSelectAll = (orderIds: number[]) => {
    if (selectedOrders.length === orderIds.length && orderIds.length > 0) {
      setSelectedOrders([])
    } else {
      setSelectedOrders(orderIds)
    }
  }

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

  const filteredOrders = orders?.filter(o =>
    !symbolFilter || o.symbol.toLowerCase().includes(symbolFilter.toLowerCase())
  ) || []

  const activeOrders = filteredOrders.filter(
    (o) => o.status === OrderStatus.OPEN || o.status === OrderStatus.PENDING || o.status === OrderStatus.PARTIALLY_FILLED
  )

  const orderHistory = filteredOrders.filter(
    (o) => o.status === OrderStatus.FILLED || o.status === OrderStatus.CANCELLED || o.status === OrderStatus.REJECTED || o.status === OrderStatus.EXPIRED
  )

  return (
    <Box>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h4">Trading</Typography>
        <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
          <FormControlLabel
            control={
              <Switch
                checked={!paperTrading}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => setPaperTrading(!e.target.checked)}
                color="warning"
                size="small"
              />
            }
            label={
              <Typography variant="body2" sx={{ fontWeight: 500 }}>
                {paperTrading ? 'Paper' : 'Live'}
              </Typography>
            }
          />
          <Button
            variant="contained"
            startIcon={<Add />}
            onClick={handleCreateOrder}
          >
            Place Order
          </Button>
        </Box>
      </Box>

      {/* Balance Card */}
      <Card sx={{ mb: 3 }}>
        <CardContent>
          <Grid container spacing={2}>
            <Grid item xs={12} md={4}>
              <Typography color="text.secondary" variant="body2">
                Available Balance
              </Typography>
              <Typography variant="h4" sx={{ fontWeight: 'bold' }}>
                ${balance?.balance?.toFixed(2) || '0.00'}
              </Typography>
            </Grid>
            <Grid item xs={12} md={4}>
              <Typography color="text.secondary" variant="body2">
                Open Positions
              </Typography>
              <Typography variant="h4" sx={{ fontWeight: 'bold' }}>
                {positions?.length || 0}
              </Typography>
            </Grid>
            <Grid item xs={12} md={4}>
              <Typography color="text.secondary" variant="body2">
                Active Orders
              </Typography>
              <Typography variant="h4" sx={{ fontWeight: 'bold' }}>
                {activeOrders.length}
              </Typography>
            </Grid>
          </Grid>
        </CardContent>
      </Card>

      <Paper>
        <Tabs value={tabValue} onChange={(_, v) => setTabValue(v)}>
          <Tab label="Positions" />
          <Tab label="Active Orders" />
          <Tab label="Order History" />
        </Tabs>

        <TabPanel value={tabValue} index={0}>
          {positionsLoading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', p: 5 }}>
              <CircularProgress />
            </Box>
          ) : positions && positions.length > 0 ? (
            <Grid container spacing={2} sx={{ p: 2 }}>
              {positions.map((position: PositionResponse) => (
                <Grid item xs={12} md={6} key={position.symbol}>
                  <PositionCard
                    position={position}
                    paperTrading={paperTrading}
                    onClose={() => {
                      // Position closing will be handled in PositionCard
                      queryClient.invalidateQueries({ queryKey: ['positions'] })
                    }}
                  />
                </Grid>
              ))}
            </Grid>
          ) : (
            <Box sx={{ p: 5, textAlign: 'center' }}>
              <Typography variant="body1" color="text.secondary">
                No open positions
              </Typography>
            </Box>
          )}
        </TabPanel>

        <TabPanel value={tabValue} index={1}>
          <Box sx={{ px: 2, pb: 2, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Box sx={{ display: 'flex', gap: 2, alignItems: 'center' }}>
              <TextField
                size="small"
                placeholder="Filter Symbol..."
                value={symbolFilter}
                onChange={(e) => setSymbolFilter(e.target.value)}
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <Search />
                    </InputAdornment>
                  ),
                }}
              />
              {activeOrders.length > 0 && (
                <ButtonGroup size="small" variant="outlined">
                  <Button
                    color="error"
                    startIcon={<DeleteSweep />}
                    onClick={handleCancelSelected}
                    disabled={selectedOrders.length === 0 || cancelMultipleOrdersMutation.isPending}
                  >
                    Cancel Selected ({selectedOrders.length})
                  </Button>
                  <Button
                    color="error"
                    startIcon={<ClearAll />}
                    onClick={handleCancelAll}
                    disabled={activeOrders.length === 0 || cancelAllOrdersMutation.isPending}
                  >
                    Cancel All
                  </Button>
                </ButtonGroup>
              )}
            </Box>
          </Box>
          <Divider />
          {ordersLoading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', p: 5 }}>
              <CircularProgress />
            </Box>
          ) : activeOrders.length > 0 ? (
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell padding="checkbox">
                      <Checkbox
                        indeterminate={selectedOrders.length > 0 && selectedOrders.length < activeOrders.length}
                        checked={activeOrders.length > 0 && selectedOrders.length === activeOrders.length}
                        onChange={() => handleSelectAll(activeOrders.map(o => o.id))}
                      />
                    </TableCell>
                    <TableCell>Time</TableCell>
                    <TableCell>Symbol</TableCell>
                    <TableCell>Side</TableCell>
                    <TableCell>Type</TableCell>
                    <TableCell align="right">Quantity</TableCell>
                    <TableCell align="right">Price</TableCell>
                    <TableCell align="right">Filled</TableCell>
                    <TableCell>Status</TableCell>
                    <TableCell align="right">Actions</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {activeOrders.map((order: OrderResponse) => (
                    <TableRow
                      key={order.id}
                      hover
                      onClick={() => handleSelectOrder(order.id)}
                      sx={{ cursor: 'pointer' }}
                    >
                      <TableCell padding="checkbox">
                        <Checkbox
                          checked={selectedOrders.includes(order.id)}
                          onChange={() => handleSelectOrder(order.id)}
                          onClick={(e) => e.stopPropagation()}
                        />
                      </TableCell>
                      <TableCell>
                        {formatDate(order.created_at, generalSettings)}
                      </TableCell>
                      <TableCell>{order.symbol}</TableCell>
                      <TableCell>
                        <Chip
                          label={order.side}
                          size="small"
                          color={order.side === OrderSide.BUY ? 'success' : 'error'}
                          icon={order.side === OrderSide.BUY ? <TrendingUp /> : <TrendingDown />}
                        />
                      </TableCell>
                      <TableCell>
                        {order.order_type.replace('_', ' ')}
                      </TableCell>
                      <TableCell align="right">
                        {Number(order.quantity).toFixed(8)}
                      </TableCell>
                      <TableCell align="right">
                        {order.price ? `$${Number(order.price).toFixed(2)}` : 'Market'}
                      </TableCell>
                      <TableCell align="right">
                        {Number(order.filled_quantity).toFixed(8)} / {Number(order.quantity).toFixed(8)}
                      </TableCell>
                      <TableCell>
                        <Chip
                          label={order.status}
                          size="small"
                          color={getStatusColor(order.status) as any}
                        />
                      </TableCell>
                      <TableCell align="right">
                        <Tooltip title="Cancel Order">
                          <IconButton
                            size="small"
                            color="error"
                            onClick={(e) => {
                              e.stopPropagation()
                              handleCancelOrder(order.id)
                            }}
                            disabled={cancelOrderMutation.isPending}
                          >
                            <Cancel />
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          ) : (
            <Box sx={{ p: 5, textAlign: 'center' }}>
              <Typography variant="body1" color="text.secondary">
                No active orders
              </Typography>
            </Box>
          )}
        </TabPanel>

        <TabPanel value={tabValue} index={2}>
          <Box sx={{ px: 2, pb: 2 }}>
            <TextField
              size="small"
              placeholder="Filter Symbol..."
              value={symbolFilter}
              onChange={(e) => setSymbolFilter(e.target.value)}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <Search />
                  </InputAdornment>
                ),
              }}
            />
          </Box>
          <Divider />
          {ordersLoading ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', p: 5 }}>
              <CircularProgress />
            </Box>
          ) : orderHistory.length > 0 ? (
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>Time</TableCell>
                    <TableCell>Symbol</TableCell>
                    <TableCell>Side</TableCell>
                    <TableCell>Type</TableCell>
                    <TableCell align="right">Quantity</TableCell>
                    <TableCell align="right">Price</TableCell>
                    <TableCell align="right">Filled</TableCell>
                    <TableCell align="right">Fee</TableCell>
                    <TableCell>Status</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {orderHistory.slice(0, 50).map((order: OrderResponse) => (
                    <TableRow key={order.id}>
                      <TableCell>
                        {formatDate(order.created_at, generalSettings)}
                      </TableCell>
                      <TableCell>{order.symbol}</TableCell>
                      <TableCell>
                        <Chip
                          label={order.side}
                          size="small"
                          color={order.side === OrderSide.BUY ? 'success' : 'error'}
                        />
                      </TableCell>
                      <TableCell>
                        {order.order_type.replace('_', ' ')}
                      </TableCell>
                      <TableCell align="right">
                        {Number(order.quantity).toFixed(8)}
                      </TableCell>
                      <TableCell align="right">
                        {order.average_fill_price
                          ? `$${Number(order.average_fill_price).toFixed(2)}`
                          : order.price
                            ? `$${Number(order.price).toFixed(2)}`
                            : 'Market'}
                      </TableCell>
                      <TableCell align="right">
                        {Number(order.filled_quantity).toFixed(8)}
                      </TableCell>
                      <TableCell align="right">
                        ${Number(order.fee).toFixed(2)}
                      </TableCell>
                      <TableCell>
                        <Chip
                          label={order.status}
                          size="small"
                          color={getStatusColor(order.status) as any}
                        />
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          ) : (
            <Box sx={{ p: 5, textAlign: 'center' }}>
              <Typography variant="body1" color="text.secondary">
                No order history
              </Typography>
            </Box>
          )}
        </TabPanel>
      </Paper>

      <OrderForm
        open={orderDialogOpen}
        onClose={() => setOrderDialogOpen(false)}
        exchanges={exchanges || []}
        paperTrading={paperTrading}
        onSuccess={() => {
          setOrderDialogOpen(false)
        }}
      />
    </Box>
  )
}

