import React, { useState } from 'react';
import {
  Box,
  Typography,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  TablePagination,
  Chip,
  CircularProgress,
  Alert,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Grid,
  Card,
  CardContent,
  List,
  ListItem,
  ListItemText,
  Divider,
  Link
} from '@mui/material';
import { format } from 'date-fns';
import { useNavigate } from 'react-router-dom';
import { useUserOrders, useUserOrder } from '../hooks/apiHooks';
import ProductImage from '../components/ProductImage';

import useBrandingSettings from '@hooks/brandingHooks';

const UserOrdersPage = () => {
  const navigate = useNavigate();
  const { data: brandingSettings } = useBrandingSettings();
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [viewDialogOpen, setViewDialogOpen] = useState(false);
  const [selectedOrderId, setSelectedOrderId] = useState(null);
  
  // Fetch user's orders
  const { data: orders, isLoading, error } = useUserOrders();
  
  // Fetch selected order details when dialog is open
  const { 
    data: orderDetails, 
    isLoading: isLoadingDetails,
  } = useUserOrder(selectedOrderId);
  
  // Handle pagination
  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };
  
  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };
  
  // Handle opening order details dialog
  const handleViewOrder = (orderId) => {
    setSelectedOrderId(orderId);
    setViewDialogOpen(true);
  };
  
  // Close view dialog
  const handleCloseViewDialog = () => {
    setViewDialogOpen(false);
    setSelectedOrderId(null);
  };
  
  // Format date
  const formatDate = (dateString) => {
    if (!dateString) return 'N/A';
    try {
      return format(new Date(dateString), 'MMM d, yyyy h:mm a');
    } catch (error) {
      return dateString;
    }
  };
  
  // 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 your orders: {error.message}
      </Alert>
    );
  }
  
  // Paginated orders
  const paginatedOrders = orders?.slice(
    page * rowsPerPage,
    page * rowsPerPage + rowsPerPage
  ) || [];
  
  return (
    <Box>
      <Typography variant="h4" component="h1" gutterBottom>
        {brandingSettings?.orders_title || `My Orders`}
      </Typography>
      
      {/* Orders Table */}
      <Paper variant="outlined">
        <TableContainer>
          <Table>
            <TableHead>
              <TableRow>
                <TableCell>Order ID</TableCell>
                <TableCell>Date</TableCell>
                <TableCell>Status</TableCell>
                <TableCell align="right">Total</TableCell>
                <TableCell>Items</TableCell>
                <TableCell></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>{formatDate(order.created_at)}</TableCell>
                    <TableCell>
                      <Chip
                        label={order.status}
                        color={getStatusColor(order.status)}
                        size="small"
                      />
                    </TableCell>
                    <TableCell align="right">
                      ${parseFloat(order.total_amount).toFixed(2)}
                    </TableCell>
                    <TableCell>{order.total_items || 0}</TableCell>
                    <TableCell>
                      <Button
                        variant="outlined"
                        size="small"
                        onClick={() => handleViewOrder(order.id)}
                      >
                        View Details
                      </Button>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={6} align="center">
                    <Typography variant="body1" py={3}>
                        {brandingSettings?.orders_empty || `You have not placed any orders`}
                    </Typography>
                    <Button
                      variant="contained"
                      onClick={() => navigate('/products')}
                      sx={{ mt: 2 }}
                    >
                      Browse 
                      {` ${brandingSettings?.product_title || `Products`}`}
                    </Button>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
        
        {orders && orders.length > 0 && (
          <TablePagination
            rowsPerPageOptions={[5, 10, 25]}
            component="div"
            count={orders.length}
            rowsPerPage={rowsPerPage}
            page={page}
            onPageChange={handleChangePage}
            onRowsPerPageChange={handleChangeRowsPerPage}
          />
        )}
      </Paper>
      
      {/* Order Details Dialog */}
      <Dialog
        open={viewDialogOpen}
        onClose={handleCloseViewDialog}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          Order Details
          {orderDetails && (
            <Typography variant="caption" display="block" sx={{ mt: 1 }}>
              Order ID: {orderDetails.id}
            </Typography>
          )}
        </DialogTitle>
        <DialogContent dividers>
          {isLoadingDetails ? (
            <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>
              
              {/* Shipping Address */}
              <Grid item xs={12} md={6}>
                <Card variant="outlined">
                  <CardContent>
                    <Typography variant="h6" gutterBottom>
                      Shipping Address
                    </Typography>
                    <Divider sx={{ mb: 2 }} />
                    
                    <Typography variant="body2" sx={{ whiteSpace: 'pre-line' }}>
                      {orderDetails.shipping_address}
                    </Typography>
                  </CardContent>
                </Card>
              </Grid>
              
              {/* Shipping Information - Show only for shipped orders */}
              {orderDetails.status === 'shipped' && orderDetails.shipping_info && (
                <Grid item xs={12}>
                  <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 (
                          <Grid container spacing={2}>
                            <Grid item xs={12} sm={6}>
                              <Typography variant="subtitle2" color="text.secondary">
                                Shipping 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>
                            
                            <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>
                            )}
                          </Grid>
                        );
                      })()}
                    </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>
                                    </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={handleCloseViewDialog}>Close</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default UserOrdersPage;