import React, { useState } from 'react';
import {
  Box,
  Typography,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Chip,
  Grid,
  Card,
  CardContent,
  IconButton,
  Alert,
  Divider,
  CircularProgress
} from '@mui/material';
import {
  Edit as EditIcon,
  Visibility as ViewIcon,
  TrendingUp as TrendingUpIcon,
  TrendingDown as TrendingDownIcon,
  AccountBalance as BalanceIcon,
  SwapHoriz as SwapIcon,
  Refresh as RefreshIcon
} from '@mui/icons-material';
import { useQuery, useMutation, useQueryClient } from 'react-query';
import apiClient from '../../request/http-common';

const TradingManagement = () => {
  const [filters, setFilters] = useState({
    status: 'all',
    order_type: 'all',
    trading_type: 'all'
  });
  const [selectedOrder, setSelectedOrder] = useState(null);
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [viewDialogOpen, setViewDialogOpen] = useState(false);
  const [editForm, setEditForm] = useState({
    profit: '',
    percentage: '',
    status: '',
    admin_notes: ''
  });

  const queryClient = useQueryClient();

  // Fetch trading orders for admin
  const { data: ordersData, isLoading, refetch } = useQuery(
    ['admin-trading-orders', filters],
    async () => {
      const params = new URLSearchParams({
        per_page: 50,
        ...filters
      });
      return await apiClient.get(`/api/admin/trading-orders?${params}`);
    },
    {
      refetchInterval: 30000, // Refresh every 30 seconds
      onError: (err) => {
        console.error('Error fetching trading orders:', err);
      }
    }
  );

  // Modify trade mutation
  const { mutate: modifyTrade, isLoading: isModifying } = useMutation(
    async (data) => {
      return await apiClient.post('/api/admin/modify-trade', data);
    },
    {
      onSuccess: () => {
        queryClient.invalidateQueries(['admin-trading-orders']);
        setEditDialogOpen(false);
        setSelectedOrder(null);
        localStorage.setItem('notification', JSON.stringify({
          message: 'Trade modified successfully',
          type: 'success'
        }));
        const event = new Event('newMessage');
        window.dispatchEvent(event);
      },
      onError: (err) => {
        console.error('Error modifying trade:', err);
        localStorage.setItem('notification', JSON.stringify({
          message: err.response?.data?.message || 'Failed to modify trade',
          type: 'error'
        }));
        const event = new Event('newMessage');
        window.dispatchEvent(event);
      }
    }
  );

  const handleEditClick = (order) => {
    setSelectedOrder(order);
    setEditForm({
      profit: order.profit || '',
      percentage: order.percentage || '',
      status: order.status || '',
      admin_notes: order.admin_notes || ''
    });
    setEditDialogOpen(true);
  };

  const handleViewClick = (order) => {
    setSelectedOrder(order);
    setViewDialogOpen(true);
  };

  const handleEditSubmit = () => {
    if (!selectedOrder) return;
    
    modifyTrade({
      trading_id: selectedOrder.id,
      ...editForm
    });
  };

  const formatCurrency = (amount) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 2
    }).format(amount || 0);
  };

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const getStatusColor = (status) => {
    switch (status) {
      case 'open': return 'primary';
      case 'closed': return 'success';
      case 'cancelled': return 'error';
      default: return 'default';
    }
  };

  // Calculate statistics
  const calculateStats = () => {
    if (!ordersData?.data?.tradings?.data) return { total: 0, open: 0, closed: 0, volume: 0 };
    
    const orders = ordersData.data.tradings.data;
    return {
      total: ordersData.data.tradings.total || orders.length,
      open: orders.filter(order => order.status === 'open').length,
      closed: orders.filter(order => order.status === 'closed').length,
      volume: orders.reduce((sum, order) => sum + parseFloat(order.amount || 0), 0)
    };
  };

  const stats = calculateStats();

  return (
    <Box sx={{ p: 3 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h4" sx={{ fontWeight: 'bold', color: '#1976d2' }}>
          🔧 Trading Management Dashboard
        </Typography>
        <Button
          variant="outlined"
          startIcon={<RefreshIcon />}
          onClick={() => refetch()}
          disabled={isLoading}
        >
          Refresh
        </Button>
      </Box>

      {/* Statistics Cards */}
      <Grid container spacing={3} sx={{ mb: 3 }}>
        <Grid item xs={12} sm={6} md={3}>
          <Card sx={{ bgcolor: '#f5f5f5', borderLeft: '4px solid #1976d2' }}>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography color="textSecondary" gutterBottom variant="body2">
                    Total Orders
                  </Typography>
                  <Typography variant="h5" color="primary" fontWeight="bold">
                    {stats.total}
                  </Typography>
                </Box>
                <BalanceIcon color="primary" sx={{ fontSize: 40 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Card sx={{ bgcolor: '#e3f2fd', borderLeft: '4px solid #2196f3' }}>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography color="textSecondary" gutterBottom variant="body2">
                    Open Orders
                  </Typography>
                  <Typography variant="h5" color="primary" fontWeight="bold">
                    {stats.open}
                  </Typography>
                </Box>
                <TrendingUpIcon color="primary" sx={{ fontSize: 40 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Card sx={{ bgcolor: '#e8f5e8', borderLeft: '4px solid #4caf50' }}>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography color="textSecondary" gutterBottom variant="body2">
                    Closed Orders
                  </Typography>
                  <Typography variant="h5" color="success.main" fontWeight="bold">
                    {stats.closed}
                  </Typography>
                </Box>
                <TrendingDownIcon color="success" sx={{ fontSize: 40 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} sm={6} md={3}>
          <Card sx={{ bgcolor: '#fff3e0', borderLeft: '4px solid #ff9800' }}>
            <CardContent>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <Box>
                  <Typography color="textSecondary" gutterBottom variant="body2">
                    Total Volume
                  </Typography>
                  <Typography variant="h5" color="info.main" fontWeight="bold">
                    {formatCurrency(stats.volume)}
                  </Typography>
                </Box>
                <SwapIcon color="info" sx={{ fontSize: 40 }} />
              </Box>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      {/* Filters */}
      <Paper sx={{ p: 2, mb: 3, bgcolor: '#fafafa' }}>
        <Typography variant="h6" sx={{ mb: 2, color: '#333' }}>🔍 Filters</Typography>
        <Grid container spacing={2}>
          <Grid item xs={12} sm={4}>
            <FormControl fullWidth size="small">
              <InputLabel>Status</InputLabel>
              <Select
                value={filters.status}
                label="Status"
                onChange={(e) => setFilters({...filters, status: e.target.value})}
              >
                <MenuItem value="all">All Status</MenuItem>
                <MenuItem value="open">Open</MenuItem>
                <MenuItem value="closed">Closed</MenuItem>
                <MenuItem value="cancelled">Cancelled</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12} sm={4}>
            <FormControl fullWidth size="small">
              <InputLabel>Order Type</InputLabel>
              <Select
                value={filters.order_type}
                label="Order Type"
                onChange={(e) => setFilters({...filters, order_type: e.target.value})}
              >
                <MenuItem value="all">All Types</MenuItem>
                <MenuItem value="Limit">Limit</MenuItem>
                <MenuItem value="Market">Market</MenuItem>
                <MenuItem value="TWAP">TWAP</MenuItem>
                <MenuItem value="Iceberg">Iceberg</MenuItem>
                <MenuItem value="Scaled Order">Scaled Order</MenuItem>
                <MenuItem value="Trailing Stop">Trailing Stop</MenuItem>
                <MenuItem value="OCO">OCO</MenuItem>
                <MenuItem value="Conditional">Conditional</MenuItem>
                <MenuItem value="TP/SL">TP/SL</MenuItem>
                <MenuItem value="Chase Limit Order">Chase Limit Order</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12} sm={4}>
            <FormControl fullWidth size="small">
              <InputLabel>Trading Type</InputLabel>
              <Select
                value={filters.trading_type}
                label="Trading Type"
                onChange={(e) => setFilters({...filters, trading_type: e.target.value})}
              >
                <MenuItem value="all">All Types</MenuItem>
                <MenuItem value="Spot">Spot</MenuItem>
                <MenuItem value="Futures">Futures</MenuItem>
              </Select>
            </FormControl>
          </Grid>
        </Grid>
      </Paper>

      {/* Orders Table */}
      <TableContainer component={Paper} sx={{ mb: 3 }}>
        <Table>
          <TableHead sx={{ bgcolor: '#f5f5f5' }}>
            <TableRow>
              <TableCell><strong>Order ID</strong></TableCell>
              <TableCell><strong>User</strong></TableCell>
              <TableCell><strong>Type</strong></TableCell>
              <TableCell><strong>Trading Type</strong></TableCell>
              <TableCell><strong>Pair</strong></TableCell>
              <TableCell><strong>Amount</strong></TableCell>
              <TableCell><strong>Profit/Loss</strong></TableCell>
              <TableCell><strong>Status</strong></TableCell>
              <TableCell><strong>Created</strong></TableCell>
              <TableCell><strong>Actions</strong></TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {isLoading ? (
              <TableRow>
                <TableCell colSpan={10} align="center" sx={{ py: 4 }}>
                  <CircularProgress />
                  <Typography sx={{ mt: 1 }}>⏳ Loading orders...</Typography>
                </TableCell>
              </TableRow>
            ) : ordersData?.data?.tradings?.data?.length > 0 ? (
              ordersData.data.tradings.data.map((order) => (
                <TableRow key={order.id} hover sx={{ '&:hover': { bgcolor: '#f9f9f9' } }}>
                  <TableCell>
                    <Typography variant="body2" fontWeight="bold" color="primary">
                      #{order.id}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <Box>
                      <Typography variant="body2" fontWeight="bold">
                        {order.user?.name || 'N/A'}
                      </Typography>
                      <Typography variant="caption" color="textSecondary">
                        ID: {order.user_id}
                      </Typography>
                    </Box>
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2" fontWeight="500">
                      {order.order_type}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <Chip 
                      label={order.trading_type || 'Spot'} 
                      size="small"
                      variant="outlined"
                      color={order.trading_type === 'Futures' ? 'warning' : 'info'}
                    />
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2" fontWeight="500">
                      {order.pair}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2" fontWeight="500">
                      {formatCurrency(order.amount)}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <Typography 
                      variant="body2"
                      fontWeight="bold"
                      color={parseFloat(order.profit || 0) >= 0 ? 'success.main' : 'error.main'}
                    >
                      {formatCurrency(order.profit)}
                    </Typography>
                    {order.percentage && (
                      <Typography variant="caption" display="block" color="textSecondary">
                        ({order.percentage}%)
                      </Typography>
                    )}
                  </TableCell>
                  <TableCell>
                    <Chip 
                      label={order.status} 
                      size="small"
                      color={getStatusColor(order.status)}
                      sx={{ textTransform: 'capitalize' }}
                    />
                    {order.admin_modified && (
                      <Chip 
                        label="Modified" 
                        size="small" 
                        color="warning" 
                        variant="outlined"
                        sx={{ ml: 0.5 }}
                      />
                    )}
                  </TableCell>
                  <TableCell>
                    <Typography variant="body2">
                      {formatDate(order.created_at)}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <IconButton 
                      size="small" 
                      onClick={() => handleViewClick(order)}
                      color="info"
                      title="View Details"
                      sx={{ mr: 1 }}
                    >
                      <ViewIcon />
                    </IconButton>
                    <IconButton 
                      size="small" 
                      onClick={() => handleEditClick(order)}
                      color="primary"
                      title="Edit Order"
                    >
                      <EditIcon />
                    </IconButton>
                  </TableCell>
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={10} align="center" sx={{ py: 4 }}>
                  <Typography>📭 No orders found</Typography>
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </TableContainer>

      {/* Edit Dialog */}
      <Dialog open={editDialogOpen} onClose={() => setEditDialogOpen(false)} maxWidth="sm" fullWidth>
        <DialogTitle sx={{ bgcolor: '#f5f5f5', color: '#1976d2' }}>
          ✏️ Modify Trading Order #{selectedOrder?.id}
        </DialogTitle>
        <DialogContent>
          <Alert severity="info" sx={{ mt: 2, mb: 2 }}>
            You are modifying a live trading order. Changes will be logged for audit purposes.
          </Alert>
          <Grid container spacing={2}>
            <Grid item xs={6}>
              <TextField
                fullWidth
                label="Profit/Loss ($)"
                type="number"
                value={editForm.profit}
                onChange={(e) => setEditForm({...editForm, profit: e.target.value})}
                margin="normal"
                inputProps={{ step: 0.01 }}
              />
            </Grid>
            <Grid item xs={6}>
              <TextField
                fullWidth
                label="Percentage (%)"
                type="number"
                value={editForm.percentage}
                onChange={(e) => setEditForm({...editForm, percentage: e.target.value})}
                margin="normal"
                inputProps={{ step: 0.01 }}
              />
            </Grid>
            <Grid item xs={12}>
              <FormControl fullWidth margin="normal">
                <InputLabel>Status</InputLabel>
                <Select
                  value={editForm.status}
                  label="Status"
                  onChange={(e) => setEditForm({...editForm, status: e.target.value})}
                >
                  <MenuItem value="open">Open</MenuItem>
                  <MenuItem value="closed">Closed</MenuItem>
                  <MenuItem value="cancelled">Cancelled</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Admin Notes"
                multiline
                rows={3}
                value={editForm.admin_notes}
                onChange={(e) => setEditForm({...editForm, admin_notes: e.target.value})}
                margin="normal"
                placeholder="Add any notes about this modification..."
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions sx={{ p: 2 }}>
          <Button onClick={() => setEditDialogOpen(false)} variant="outlined">
            Cancel
          </Button>
          <Button 
            onClick={handleEditSubmit} 
            variant="contained" 
            disabled={isModifying}
            color="primary"
          >
            {isModifying ? (
              <>
                <CircularProgress size={20} sx={{ mr: 1 }} />
                Saving...
              </>
            ) : (
              '💾 Save Changes'
            )}
          </Button>
        </DialogActions>
      </Dialog>

      {/* View Dialog */}
      <Dialog open={viewDialogOpen} onClose={() => setViewDialogOpen(false)} maxWidth="lg" fullWidth>
        <DialogTitle sx={{ bgcolor: '#f5f5f5', color: '#1976d2' }}>
          📊 Trading Order Details #{selectedOrder?.id}
        </DialogTitle>
        <DialogContent>
          {selectedOrder && (
            <Grid container spacing={3} sx={{ mt: 1 }}>
              <Grid item xs={12} md={6}>
                <Card variant="outlined" sx={{ bgcolor: '#fafafa' }}>
                  <CardContent>
                    <Typography variant="h6" gutterBottom color="primary">
                      📋 Basic Information
                    </Typography>
                    <Divider sx={{ mb: 2 }} />
                    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body2" color="textSecondary">Order ID:</Typography>
                        <Typography variant="body2" fontWeight="bold">#{selectedOrder.id}</Typography>
                      </Box>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body2" color="textSecondary">User:</Typography>
                        <Typography variant="body2">{selectedOrder.user?.name || 'N/A'}</Typography>
                      </Box>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body2" color="textSecondary">User ID:</Typography>
                        <Typography variant="body2">{selectedOrder.user_id}</Typography>
                      </Box>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body2" color="textSecondary">Order Type:</Typography>
                        <Typography variant="body2" fontWeight="bold">{selectedOrder.order_type}</Typography>
                      </Box>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body2" color="textSecondary">Trading Type:</Typography>
                        <Typography variant="body2">{selectedOrder.trading_type || 'Spot'}</Typography>
                      </Box>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body2" color="textSecondary">Pair:</Typography>
                        <Typography variant="body2" fontWeight="bold">{selectedOrder.pair}</Typography>
                      </Box>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body2" color="textSecondary">Status:</Typography>
                        <Chip 
                          label={selectedOrder.status} 
                          size="small"
                          color={getStatusColor(selectedOrder.status)}
                        />
                      </Box>
                    </Box>
                  </CardContent>
                </Card>
              </Grid>

              <Grid item xs={12} md={6}>
                <Card variant="outlined" sx={{ bgcolor: '#fafafa' }}>
                  <CardContent>
                    <Typography variant="h6" gutterBottom color="success.main">
                      💰 Financial Details
                    </Typography>
                    <Divider sx={{ mb: 2 }} />
                    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body2" color="textSecondary">Amount:</Typography>
                        <Typography variant="body2" fontWeight="bold">{formatCurrency(selectedOrder.amount)}</Typography>
                      </Box>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                        <Typography variant="body2" color="textSecondary">Entry Point:</Typography>
                        <Typography variant="body2">{formatCurrency(selectedOrder.entry_point)}</Typography>
                      </Box>
                      {selectedOrder.limit_price && (
                        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                          <Typography variant="body2" color="textSecondary">Limit Price:</Typography>
                          <Typography variant="body2">{formatCurrency(selectedOrder.limit_price)}</Typography>
                        </Box>
                      )}
                      {selectedOrder.order_quantity && (
                        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                          <Typography variant="body2" color="textSecondary">Quantity:</Typography>
                          <Typography variant="body2">{selectedOrder.order_quantity}</Typography>
                        </Box>
                      )}
                      {selectedOrder.take_profit && (
                        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                          <Typography variant="body2" color="textSecondary">Take Profit:</Typography>
                          <Typography variant="body2" color="success.main">{formatCurrency(selectedOrder.take_profit)}</Typography>
                        </Box>
                      )}
                      {selectedOrder.stop_loss && (
                        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                          <Typography variant="body2" color="textSecondary">Stop Loss:</Typography>
                          <Typography variant="body2" color="error.main">{formatCurrency(selectedOrder.stop_loss)}</Typography>
                        </Box>
                      )}
                      <Box sx={{ display: 'flex', justifyContent: 'space-between', bgcolor: 'white', p: 1, borderRadius: 1 }}>
                        <Typography variant="body2" color="textSecondary">Profit/Loss:</Typography>
                        <Typography 
                          variant="body2" 
                          color={parseFloat(selectedOrder.profit || 0) >= 0 ? 'success.main' : 'error.main'}
                          fontWeight="bold"
                        >
                          {formatCurrency(selectedOrder.profit)} ({selectedOrder.percentage || 0}%)
                        </Typography>
                      </Box>
                    </Box>
                  </CardContent>
                </Card>
              </Grid>

              {(selectedOrder.admin_modified || selectedOrder.admin_notes) && (
                <Grid item xs={12}>
                  <Card variant="outlined" sx={{ bgcolor: '#fff3e0' }}>
                    <CardContent>
                      <Typography variant="h6" gutterBottom color="warning.main">
                        ⚠️ Admin Information
                      </Typography>
                      <Divider sx={{ mb: 2 }} />
                      {selectedOrder.admin_modified && (
                        <Alert severity="warning" sx={{ mb: 2 }}>
                          This order has been modified by an administrator
                          {selectedOrder.admin_modified_at && ` on ${formatDate(selectedOrder.admin_modified_at)}`}
                        </Alert>
                      )}
                      {selectedOrder.admin_notes && (
                        <Box>
                          <Typography variant="body2" color="textSecondary" gutterBottom>
                            Admin Notes:
                          </Typography>
                          <Typography variant="body2" sx={{ 
                            p: 2, 
                            bgcolor: 'white', 
                            borderRadius: 1,
                            border: '1px solid',
                            borderColor: 'divider',
                            fontStyle: 'italic'
                          }}>
                            "{selectedOrder.admin_notes}"
                          </Typography>
                        </Box>
                      )}
                    </CardContent>
                  </Card>
                </Grid>
              )}
            </Grid>
          )}
        </DialogContent>
        <DialogActions sx={{ p: 2 }}>
          <Button onClick={() => setViewDialogOpen(false)} variant="contained">
            Close
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default TradingManagement; 