import React, { useState } from 'react';
import {
  Box,
  Typography,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TablePagination,
  IconButton,
  TextField,
  InputAdornment,
  Chip,
  CircularProgress,
  Alert,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Button,
  Grid,
  Card,
  CardContent,
  List,
  ListItem,
  ListItemText,
  Divider,
  MenuItem,
  FormControl,
  InputLabel,
  Select,
  Tooltip,
  Link
} from '@mui/material';
import {
  Search as SearchIcon,
  Clear as ClearIcon,
  Visibility as ViewIcon,
  LocalShipping as ShippingIcon,
  CheckCircle as CheckCircleIcon
} from '@mui/icons-material';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import apiClient from '@services/api';
import { format } from 'date-fns';
import ProductImage from '@components/ProductImage';
import OrderStatusDialog from '@components/OrderStatusDialog';
import useBrandingSettings from '@hooks/brandingHooks';
const { data: brandingSettings } = useBrandingSettings();

const AdminOrdersPage = () => {
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [search, setSearch] = useState('');
  const [viewDialogOpen, setViewDialogOpen] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState(null);
  const [orderDetails, setOrderDetails] = useState(null);
  const [statusDialogOpen, setStatusDialogOpen] = useState(false);
  const { data: brandingSettings } = useBrandingSettings();
  const [newStatus, setNewStatus] = useState('');
  
  const queryClient = useQueryClient();

  // Fetch orders
  const {
    data: orders,
    isLoading,
    error
  } = useQuery({
    queryKey: ['admin-orders', search],
    queryFn: async () => {
      const response = await apiClient.get('/admin/orders');
      return response.data;
    }
  });

  // Fetch single order
  const {
    isLoading: isLoadingOrderDetails,
    refetch: fetchOrderDetails
  } = useQuery({
    queryKey: ['admin-order-details', selectedOrder?.id],
    queryFn: async () => {
      if (!selectedOrder?.id) return null;
      
      const response = await apiClient.get(`/admin/orders/${selectedOrder.id}`);
      setOrderDetails(response.data);
      return response.data;
    },
    enabled: false // Only run when manually triggered
  });

  // Update order status mutation
  const updateOrderStatus = useMutation({
    mutationFn: async ({ orderId, status }) => {
      const response = await apiClient.patch(`/admin/orders/${orderId}`, { status });
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['admin-orders'] });
      if (selectedOrder) {
        queryClient.invalidateQueries({ queryKey: ['admin-order-details', selectedOrder.id] });
      }
      setStatusDialogOpen(false);
    }
  });

  // Filter orders by search term
  const filteredOrders = orders ? orders.filter(order => {
    const searchTerm = search.toLowerCase();
    return (
      order.id.toLowerCase().includes(searchTerm) ||
      (order.email && order.email.toLowerCase().includes(searchTerm)) ||
      (order.first_name && order.first_name.toLowerCase().includes(searchTerm)) ||
      (order.last_name && order.last_name.toLowerCase().includes(searchTerm)) ||
      (order.status && order.status.toLowerCase().includes(searchTerm))
    );
  }) : [];

  // Paginated orders
  const paginatedOrders = filteredOrders.slice(
    page * rowsPerPage,
    page * rowsPerPage + rowsPerPage
  );

  // Handle search change
  const handleSearchChange = (event) => {
    setSearch(event.target.value);
    setPage(0);
  };

  // Clear search
  const handleClearSearch = () => {
    setSearch('');
    setPage(0);
  };

  // Handle page change
  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  // Handle rows per page change
  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  // Handle view order details
  const handleViewOrder = async (order) => {
    setSelectedOrder(order);
    setViewDialogOpen(true);
    await fetchOrderDetails();
  };

  // Close view dialog
  const handleCloseViewDialog = () => {
    setViewDialogOpen(false);
    setOrderDetails(null);
    setSelectedOrder(null);
  };

  // Format date
  const formatDate = (dateString) => {
    if (!dateString) return '';
    try {
      return format(new Date(dateString), 'MMM d, yyyy h:mm a');
    } catch (error) {
      return dateString;
    }
  };

  // Handle opening status change dialog
  const handleOpenStatusDialog = (order) => {
    setSelectedOrder(order);
    setStatusDialogOpen(true);
  };

  // Handle status change
  const handleStatusChange = (event) => {
    setNewStatus(event.target.value);
  };

  // Handle save status
  const handleSaveStatus = () => {
    if (selectedOrder && newStatus) {
      updateOrderStatus.mutate({
        orderId: selectedOrder.id,
        status: newStatus
      });
    }
  };

  // Helper function to get status chip color
  const getStatusColor = (status) => {
    switch (status) {
      case 'pending':
        return 'default';
      case 'processing':
        return 'primary';
      case 'shipped':
        return 'info';
      case 'delivered':
        return 'success';
      case 'cancelled':
        return 'error';
      case 'refunded':
        return 'warning';
      default:
        return 'default';
    }
  };

  // Loading state
  if (isLoading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  // Error state
  if (error) {
    return (
      <Alert severity="error" sx={{ my: 2 }}>
        Error loading orders: {error.message}
      </Alert>
    );
  }

  return (
    <Box>
      <Typography variant="h4" component="h1" gutterBottom>
        Orders
      </Typography>

      {/* Search Box */}
      <Paper sx={{ p: 2, mb: 3 }}>
        <TextField
          fullWidth
          placeholder="Search orders by ID, customer name, email, or status..."
          value={search}
          onChange={handleSearchChange}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon />
              </InputAdornment>
            ),
            endAdornment: search && (
              <InputAdornment position="end">
                <IconButton size="small" onClick={handleClearSearch}>
                  <ClearIcon />
                </IconButton>
              </InputAdornment>
            )
          }}
        />
      </Paper>

      {/* Orders Table */}
      <Paper>
        <TableContainer>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>Order ID</TableCell>
                <TableCell>Customer</TableCell>
                <TableCell>Date</TableCell>
                <TableCell>Status</TableCell>
                <TableCell align="right">Total</TableCell>
                <TableCell>Items</TableCell>
                <TableCell align="right">Actions</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {paginatedOrders.length > 0 ? (
                paginatedOrders.map((order) => (
                  <TableRow key={order.id}>
                    <TableCell>
                      <Typography variant="body2" sx={{ fontFamily: 'monospace' }}>
                        {order.id.substring(0, 8)}...
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2">
                        {order.first_name} {order.last_name}
                      </Typography>
                      <Typography variant="caption" color="text.secondary">
                        {order.email}
                      </Typography>
                    </TableCell>
                    <TableCell>{formatDate(order.created_at)}</TableCell>
                    <TableCell>
                      <Chip
                        label={order.status}
                        color={getStatusColor(order.status)}
                        size="small"
                        onClick={() => handleOpenStatusDialog(order)}
                      />
                    </TableCell>
                    <TableCell align="right">
                      ${parseFloat(order.total_amount).toFixed(2)}
                    </TableCell>
                    <TableCell>{order.item_count || 0}</TableCell>
                    <TableCell align="right">
                      <Tooltip title="View Details">
                        <IconButton
                          onClick={() => handleViewOrder(order)}
                          color="primary"
                        >
                          <ViewIcon />
                        </IconButton>
                      </Tooltip>
                      <Tooltip title="Change Status">
                        <IconButton
                          onClick={() => handleOpenStatusDialog(order)}
                          color="secondary"
                        >
                          <ShippingIcon />
                        </IconButton>
                      </Tooltip>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={7} align="center">
                    <Typography variant="body1" py={2}>
                      {search ? 'No orders match your search.' : 'No orders found.'}
                    </Typography>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
        <TablePagination
          rowsPerPageOptions={[5, 10, 25, 50]}
          component="div"
          count={filteredOrders.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
        />
      </Paper>

      {/* View Order Dialog */}
      <Dialog
        open={viewDialogOpen}
        onClose={handleCloseViewDialog}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          Order Details
          {selectedOrder && (
            <Typography variant="caption" display="block" sx={{ mt: 1 }}>
              Order ID: {selectedOrder.id}
            </Typography>
          )}
        </DialogTitle>
        <DialogContent dividers>
          {isLoadingOrderDetails ? (
            <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
              <CircularProgress />
            </Box>
          ) : orderDetails ? (
            <Grid container spacing={3}>
              {/* Order Summary */}
              <Grid item xs={12} md={6}>
                <Card variant="outlined">
                  <CardContent>
                    <Typography variant="h6" gutterBottom>
                      Order Summary
                    </Typography>
                    <Divider sx={{ mb: 2 }} />
                    
                    <Grid container spacing={2}>
                      <Grid item xs={4}>
                        <Typography variant="body2" color="text.secondary">
                          Date:
                        </Typography>
                      </Grid>
                      <Grid item xs={8}>
                        <Typography variant="body2">
                          {formatDate(orderDetails.created_at)}
                        </Typography>
                      </Grid>
                      
                      <Grid item xs={4}>
                        <Typography variant="body2" color="text.secondary">
                          Status:
                        </Typography>
                      </Grid>
                      <Grid item xs={8}>
                        <Chip
                          label={orderDetails.status}
                          color={getStatusColor(orderDetails.status)}
                          size="small"
                        />
                      </Grid>
                      
                      <Grid item xs={4}>
                        <Typography variant="body2" color="text.secondary">
                          Total:
                        </Typography>
                      </Grid>
                      <Grid item xs={8}>
                        <Typography variant="body2" fontWeight="bold">
                          ${parseFloat(orderDetails.total_amount).toFixed(2)}
                        </Typography>
                      </Grid>
                    </Grid>
                  </CardContent>
                </Card>
              </Grid>
              
              {/* Customer Info */}
              <Grid item xs={12} md={6}>
                <Card variant="outlined">
                  <CardContent>
                    <Typography variant="h6" gutterBottom>
                      Customer Information
                    </Typography>
                    <Divider sx={{ mb: 2 }} />
                    
                    <Typography variant="body1">
                      {orderDetails.first_name} {orderDetails.last_name}
                    </Typography>
                    <Typography variant="body2" sx={{ mb: 2 }}>
                      {orderDetails.email}
                    </Typography>
                    
                    <Typography variant="subtitle2" gutterBottom>
                      Shipping Address:
                    </Typography>
                    <Typography variant="body2" sx={{ whiteSpace: 'pre-line' }}>
                      {orderDetails.shipping_address}
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
              
              {/* Shipping Information - Only show for shipped orders */}
              {orderDetails && orderDetails.status === 'shipped' && orderDetails.shipping_info && (
                <Grid item xs={12} sx={{ mt: 2 }}>
                  <Card variant="outlined">
                    <CardContent>
                      <Typography variant="h6" gutterBottom>
                        Shipping Information
                      </Typography>
                      <Divider sx={{ mb: 2 }} />
                      
                      {(() => {
                        // Parse shipping info from JSON if needed
                        let shippingInfo = orderDetails.shipping_info;
                        if (typeof shippingInfo === 'string') {
                          try {
                            shippingInfo = JSON.parse(shippingInfo);
                          } catch (e) {
                            console.error('Failed to parse shipping info:', e);
                          }
                        }
                        
                        // Generate tracking link
                        let trackingLink = '#';
                        const shipper = shippingInfo.shipper || '';
                        const trackingNumber = shippingInfo.trackingNumber;
                        
                        if (trackingNumber) {
                          // Match exactly with the values from the dropdown
                          switch(shipper) {
                            case 'USPS':
                              trackingLink = `https://tools.usps.com/go/TrackConfirmAction?tLabels=${trackingNumber}`;
                              break;
                            case 'UPS':
                              trackingLink = `https://www.ups.com/track?tracknum=${trackingNumber}`;
                              break;
                            case 'FedEx':
                              trackingLink = `https://www.fedex.com/apps/fedextrack/?tracknumbers=${trackingNumber}`;
                              break;
                            case 'DHL':
                              trackingLink = `https://www.dhl.com/global-en/home/tracking.html?tracking-id=${trackingNumber}`;
                              break;
                            case 'Canada Post':
                              trackingLink = `https://www.canadapost-postescanada.ca/track-reperage/en#/search?searchFor=${trackingNumber}`;
                              break;
                            case 'Purolator':
                              trackingLink = `https://www.purolator.com/en/shipping/track/tracking-number/${trackingNumber}`;
                              break;
                            default:
                              trackingLink = '#';
                              break;
                          }
                        }
                        
                        return (
                          <Box>
                            <Grid container spacing={2}>
                              <Grid item xs={12} sm={6}>
                                <Typography variant="subtitle2" color="text.secondary">
                                  Carrier:
                                </Typography>
                                <Typography variant="body1">
                                  {shippingInfo.shipper || 'Not specified'}
                                </Typography>
                              </Grid>
                              
                              <Grid item xs={12} sm={6}>
                                <Typography variant="subtitle2" color="text.secondary">
                                  Tracking Number:
                                </Typography>
                                <Typography variant="body1">
                                  {trackingNumber ? (
                                    <Link href={trackingLink} target="_blank" rel="noopener noreferrer">
                                      {trackingNumber}
                                    </Link>
                                  ) : (
                                    'Not available'
                                  )}
                                </Typography>
                              </Grid>
                              
                              {shippingInfo.shipmentId && (
                                <Grid item xs={12} sm={6}>
                                  <Typography variant="subtitle2" color="text.secondary">
                                    Shipment ID:
                                  </Typography>
                                  <Typography variant="body1">
                                    {shippingInfo.shipmentId}
                                  </Typography>
                                </Grid>
                              )}
                              
                              <Grid item xs={12} sm={6}>
                                <Typography variant="subtitle2" color="text.secondary">
                                  Shipped Date:
                                </Typography>
                                <Typography variant="body1">
                                  {orderDetails.shipping_date 
                                    ? formatDate(orderDetails.shipping_date) 
                                    : (shippingInfo.shippedDate 
                                        ? formatDate(shippingInfo.shippedDate) 
                                        : 'Not available')}
                                </Typography>
                              </Grid>
                              
                              {shippingInfo.estimatedDelivery && (
                                <Grid item xs={12} sm={6}>
                                  <Typography variant="subtitle2" color="text.secondary">
                                    Estimated Delivery:
                                  </Typography>
                                  <Typography variant="body1">
                                    {shippingInfo.estimatedDelivery}
                                  </Typography>
                                </Grid>
                              )}
                              
                              {shippingInfo.customerMessage && (
                                <Grid item xs={12}>
                                  <Typography variant="subtitle2" color="text.secondary">
                                    Message to Customer:
                                  </Typography>
                                  <Paper variant="outlined" sx={{ p: 2, mt: 1, bgcolor: 'background.paper' }}>
                                    <Typography variant="body2">
                                      {shippingInfo.customerMessage}
                                    </Typography>
                                  </Paper>
                                </Grid>
                              )}
                            </Grid>
                            
                            {/* Check if a notification was sent */}
                            {orderDetails.notification_sent && (
                              <Box sx={{ mt: 2 }}>
                                <Chip 
                                  icon={<CheckCircleIcon />} 
                                  label="Shipping notification email sent" 
                                  color="success" 
                                  size="small" 
                                />
                              </Box>
                            )}
                          </Box>
                        );
                      })()}
                    </CardContent>
                  </Card>
                </Grid>
              )}


              {/* Order Items */}
              <Grid item xs={12}>
                <Card variant="outlined">
                  <CardContent>
                    <Typography variant="h6" gutterBottom>
                      Order Items
                    </Typography>
                    <Divider sx={{ mb: 2 }} />
                    
                    <List>
                      {orderDetails.items && orderDetails.items.map((item, index) => (
                        <React.Fragment key={item.id}>
                          <ListItem alignItems="flex-start">
                            <Grid container spacing={2} alignItems="center">
                              <Grid item xs={2} sm={1}>
                                <ProductImage
                                  images={item.product_images}
                                  alt={item.product_name}
                                  sx={{ width: 50, height: 50, borderRadius: 1 }}
                                />
                              </Grid>
                              <Grid item xs={10} sm={7}>
                                <ListItemText
                                  primary={item.product_name}
                                  secondary={
                                    <React.Fragment>
                                      <Typography variant="caption" component="span" color="text.primary">
                                        Category: {item.product_category}
                                      </Typography>
                                      <br />
                                      <Typography variant="caption" component="span">
                                        {item.product_description && item.product_description.substring(0, 100)}
                                        {item.product_description && item.product_description.length > 100 ? '...' : ''}
                                      </Typography>
                                    </React.Fragment>
                                  }
                                />
                              </Grid>
                              <Grid item xs={4} sm={2} textAlign="center">
                                <Typography variant="body2">
                                  ${parseFloat(item.price_at_purchase).toFixed(2)} × {item.quantity}
                                </Typography>
                              </Grid>
                              <Grid item xs={8} sm={2} textAlign="right">
                                <Typography variant="body1" fontWeight="bold">
                                  ${(parseFloat(item.price_at_purchase) * item.quantity).toFixed(2)}
                                </Typography>
                              </Grid>
                            </Grid>
                          </ListItem>
                          {index < orderDetails.items.length - 1 && <Divider />}
                        </React.Fragment>
                      ))}
                    </List>
                  </CardContent>
                </Card>
              </Grid>
            </Grid>
          ) : (
            <Typography color="error">Failed to load order details</Typography>
          )}
        </DialogContent>
        <DialogActions>
          <Button
            onClick={() => {
              if (selectedOrder) {
                handleOpenStatusDialog(selectedOrder);
              }
            }}
            color="primary"
            startIcon={<ShippingIcon />}
          >
            Change Status
          </Button>
          <Button onClick={handleCloseViewDialog}>Close</Button>
        </DialogActions>
      </Dialog>

      {/* Change Status Dialog */}
      <OrderStatusDialog
        open={statusDialogOpen}
        onClose={() => setStatusDialogOpen(false)}
        order={selectedOrder}
      />
    </Box>
  );
};

export default AdminOrdersPage;