'use client';

import React, { useEffect, useState } from 'react';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { useSnackbar } from 'notistack';
import { AppLoader } from '@/components/core/app-loader';
import {
  Box,
  Button,
  Card,
  CardContent,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  FormControl,
  InputLabel,
  MenuItem,
  Select,
  Stack,
  TextField,
  Typography,
  TableContainer,
  Table,
  TableHead,
  TableBody,
  TableRow,
  TableCell,
  useTheme,
} from '@mui/material';
import { getOrderDetails, updateOrderStatus, adminCancelOrder } from '@/services/order.service';
import { IOrder } from '@/types/order.type';

dayjs.extend(utc);

const cancelReasons = [
  'Customer Request',
  'Out of Stock',
  'Invalid Order',
  'Payment Failed',
  'Other'
];

interface OrderDetailProps {
  id: string;
}

const OrderDetail = ({ id }: OrderDetailProps) => {
  const [orderDetails, setOrderDetails] = useState<IOrder | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isCancelReasonDialogOpen, setIsCancelReasonDialogOpen] = useState(false);
  const [cancelReason, setCancelReason] = useState('');
  const [cancelReasonType, setCancelReasonType] = useState('');
  const [activeView, setActiveView] = useState<'details' | 'timeline'>('details');
  const [isImageViewerOpen, setIsImageViewerOpen] = useState(false);
  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const { enqueueSnackbar } = useSnackbar();
  const theme = useTheme();

  const handleImageClick = (imageUrl: string) => {
    setSelectedImage(imageUrl);
    setIsImageViewerOpen(true);
  };

  const handleCloseImageViewer = () => {
    setIsImageViewerOpen(false);
    setSelectedImage(null);
  };

  // Use the passed id prop
  const orderId = id;

  useEffect(() => {
    if (orderId) {
      fetchOrderDetail(orderId);
    }
  }, [orderId]);

  const fetchOrderDetail = async (id: string) => {
    try {
      setIsLoading(true);
      const response = await getOrderDetails(id);
      if (response?.data?.data) {
        setOrderDetails(response.data.data);
      }
    } catch (error) {
      console.error('Error fetching order details:', error);
      enqueueSnackbar('Failed to fetch order details', { variant: 'error' });
    } finally {
      setIsLoading(false);
    }
  };

  const handleCancelClick = () => {
    setIsCancelReasonDialogOpen(true);
  };

  const handleAdminCancelClick = () => {
    setIsCancelReasonDialogOpen(true);
  };

  const handleAdminCancelConfirm = async () => {
    if (!orderDetails || !orderId || (!cancelReasonType || (cancelReasonType === 'Other' && !cancelReason))) {
      enqueueSnackbar('Please provide a reason for cancellation', { variant: 'error' });
      return;
    }

    try {
      setIsLoading(true);
      console.log('Admin canceling order:', orderDetails._id);
      const finalReason = cancelReasonType === 'Other' ? cancelReason : cancelReasonType;
      console.log('Cancel reason:', finalReason);

      const response = await adminCancelOrder(orderDetails._id, {
        cancellationReason: finalReason
      });

      console.log('Admin cancel response:', response?.data);

      if (response?.status === 200 || response?.data?.status === 200) {
        enqueueSnackbar('Order canceled successfully by admin', { variant: 'success' });
        setIsCancelReasonDialogOpen(false);
        setCancelReason('');
        setCancelReasonType('');
        
        // Navigate back to orders list with canceled tab
        window.location.href = '/dashboard/orders?tab=canceled';
      } else {
        throw new Error(response?.data?.message || 'Failed to cancel order');
      }
    } catch (error: any) {
      console.error('Error canceling order:', error);
      enqueueSnackbar(error?.message || 'Failed to cancel order', { variant: 'error' });
    } finally {
      setIsLoading(false);
    }
  };

  const handleCancelConfirm = async () => {
    if (!orderDetails || !orderId || (!cancelReasonType || (cancelReasonType === 'Other' && !cancelReason))) {
      enqueueSnackbar('Please provide a reason for cancellation', { variant: 'error' });
      return;
    }

    try {
      setIsLoading(true);
      console.log('Canceling order:', orderDetails._id);
      console.log('Cancel reason:', cancelReasonType === 'Other' ? cancelReason : cancelReasonType);

      const response = await updateOrderStatus(orderDetails._id, {
        status: 'canceled',
        cancelReason: cancelReasonType === 'Other' ? cancelReason : cancelReasonType
      });

      console.log('Cancel response:', response?.data);

      if (response?.status === 200 || response?.data?.status === 200) {
        enqueueSnackbar('Order canceled successfully', { variant: 'success' });
        setIsCancelReasonDialogOpen(false);
        setCancelReason('');
        setCancelReasonType('');
        
        // Navigate back to orders list with canceled tab
        window.location.href = '/dashboard/orders?tab=canceled';
      } else {
        throw new Error(response?.data?.message || 'Failed to cancel order');
      }
    } catch (error: any) {
      console.error('Error canceling order:', error);
      enqueueSnackbar(error?.message || 'Failed to cancel order', { variant: 'error' });
    } finally {
      setIsLoading(false);
    }
  };

  const handleCloseCancelDialog = () => {
    setIsCancelReasonDialogOpen(false);
    setCancelReason('');
    setCancelReasonType('');
  };

  const handleMarkAsDelivered = async () => {
    if (!orderDetails || !orderId) {
      enqueueSnackbar('Order details not found', { variant: 'error' });
      return;
    }

    try {
      setIsLoading(true);
      const response = await updateOrderStatus(orderDetails._id, {
        status: 'delivered'
      });

      if (response?.status === 200 || response?.data?.status === 200) {
        enqueueSnackbar('Order marked as delivered successfully', { variant: 'success' });
        // Refresh order details
        fetchOrderDetail(orderId);
      } else {
        throw new Error(response?.data?.message || 'Failed to update order status');
      }
    } catch (error: any) {
      console.error('Error updating order status:', error);
      enqueueSnackbar(error?.message || 'Failed to update order status', { variant: 'error' });
    } finally {
      setIsLoading(false);
    }
  };

  if (!orderDetails) {
    return (
      <AppLoader size="lg" viewport="content" />
    );
  }

  return (
    <Stack spacing={1}>
      <Stack direction={'row'} justifyContent={'space-between'} alignItems={'center'} mb={2}>
        <Typography variant="h4">Order Details</Typography>
        {orderDetails.status === 'processing' && (
          <Stack direction="row" spacing={2}>
            <Button
              variant="contained"
              color="success"
              onClick={handleMarkAsDelivered}
              disabled={isLoading}
            >
              Mark as Delivered
            </Button>
            <Button
              variant="contained"
              color="error"
              onClick={handleAdminCancelClick}
              disabled={isLoading}
            >
              Admin Cancel Order
            </Button>
          </Stack>
        )}
      </Stack>

      {/* Order Status and Cancellation Reason */}
      <Card sx={{ mb: 2 }}>
        <CardContent>
          <Stack direction="row" justifyContent="space-between" alignItems="center">
            <Typography variant="h6">Order Status</Typography>
            <Chip
              label={orderDetails.status?.charAt(0).toUpperCase() + orderDetails.status?.slice(1)}
              color={
                orderDetails.status === 'delivered'
                  ? 'success'
                  : orderDetails.status === 'canceled'
                  ? 'error'
                  : 'warning'
              }
            />
          </Stack>
          {orderDetails.status === 'canceled' && orderDetails.cancelReason && (
            <Box sx={{ 
              mt: 2, 
              p: 2, 
              bgcolor: theme.palette.mode === 'dark' ? 'error.dark' : 'error.light', 
              borderRadius: 1 
            }}>
              <Typography variant="subtitle1" color={theme.palette.mode === 'dark' ? 'error.light' : 'error.main'}>
                <strong>Cancellation Reason:</strong> {orderDetails.cancelReason}
              </Typography>
            </Box>
          )}
        </CardContent>
      </Card>

      {/* Customer Information */}
      <Card sx={{ mb: 2 }}>
        <CardContent>
          <Typography variant="h6" gutterBottom>Customer Information</Typography>
          <Stack spacing={2}>
            <Box>
              <Typography component="span" fontWeight={600} color="text.primary">Name:</Typography>
              <Typography component="span" sx={{ ml: 1 }} color="text.primary">
                {orderDetails.address?.personalInfo || 'N/A'}
              </Typography>
            </Box>
            <Box>
              <Typography component="span" fontWeight={600} color="text.primary">Email:</Typography>
              <Typography component="span" sx={{ ml: 1 }} color="text.primary">
                {orderDetails.address?.additionalInfo || 'N/A'}
              </Typography>
            </Box>
            <Box>
              <Typography component="span" fontWeight={600} color="text.primary">Phone:</Typography>
              <Typography component="span" sx={{ ml: 1 }} color="text.primary">
                {orderDetails.address?.phoneNumber || 'N/A'}
              </Typography>
            </Box>
          </Stack>
        </CardContent>
      </Card>

      {/* Shipping Address Information */}
      <Card sx={{ mb: 2 }}>
        <CardContent>
          <Typography variant="h6" gutterBottom>Shipping Address</Typography>
          <Stack spacing={2}>
            <Box>
              <Typography component="span" fontWeight={600} color="text.primary">Address:</Typography>
              <Typography component="span" sx={{ ml: 1 }} color="text.primary">
                {orderDetails.address?.address || 'N/A'}
              </Typography>
            </Box>
            <Box>
              <Typography component="span" fontWeight={600} color="text.primary">City:</Typography>
              <Typography component="span" sx={{ ml: 1 }} color="text.primary">
                {orderDetails.address?.city || 'N/A'}
              </Typography>
            </Box>
            <Box>
              <Typography component="span" fontWeight={600} color="text.primary">State:</Typography>
              <Typography component="span" sx={{ ml: 1 }} color="text.primary">
                {orderDetails.address?.state || 'N/A'}
              </Typography>
            </Box>
            <Box>
              <Typography component="span" fontWeight={600} color="text.primary">Country:</Typography>
              <Typography component="span" sx={{ ml: 1 }} color="text.primary">
                {orderDetails.address?.country || 'N/A'}
              </Typography>
            </Box>
            <Box>
              <Typography component="span" fontWeight={600} color="text.primary">ZIP Code:</Typography>
              <Typography component="span" sx={{ ml: 1 }} color="text.primary">
                {orderDetails.address?.zipCode || 'N/A'}
              </Typography>
            </Box>
            <Box>
              <Typography component="span" fontWeight={600} color="text.primary">Additional Info:</Typography>
              <Typography component="span" sx={{ ml: 1 }} color="text.primary">
                {orderDetails.address?.additionalInfo || 'N/A'}
              </Typography>
            </Box>
          </Stack>
        </CardContent>
      </Card>

      {/* Order Information */}
      <Card sx={{ mb: 2 }}>
        <CardContent>
          <Typography variant="h6" gutterBottom>Order Information</Typography>
          <Stack spacing={2}>
            <Box>
              <Typography component="span" fontWeight={600} color="text.primary">Order ID:</Typography>
              <Typography component="span" sx={{ ml: 1 }} color="text.primary">
                {orderDetails.cartId || orderDetails._id}
              </Typography>
            </Box>
            <Box>
              <Typography component="span" fontWeight={600} color="text.primary">Order Date:</Typography>
              <Typography component="span" sx={{ ml: 1 }} color="text.primary">
                {orderDetails.address?.createdAt ? dayjs(orderDetails.address.createdAt).format('MMM D, YYYY h:mm A') : '-'}
              </Typography>
            </Box>
            <Box>
              <Typography component="span" fontWeight={600} color="text.primary">Subtotal:</Typography>
              <Typography component="span" sx={{ ml: 1 }} color="text.primary" fontWeight={600}>
                ${(orderDetails.subtotal || orderDetails.price || 0).toFixed(2)}
              </Typography>
            </Box>
            <Box>
              <Typography component="span" fontWeight={600} color="text.primary">Shipping Cost:</Typography>
              <Typography component="span" sx={{ ml: 1 }} color="text.secondary" fontWeight={600}>
                ${(orderDetails.shippingCost || 0).toFixed(2)}
              </Typography>
            </Box>
            <Box sx={{ 
              borderTop: '2px solid', 
              borderColor: theme.palette.mode === 'dark' ? '#4a5568' : '#e5e7eb',
              pt: 1,
              mt: 1
            }}>
              <Typography component="span" fontWeight={700} color="text.primary" variant="h6">Total Amount:</Typography>
              <Typography component="span" sx={{ ml: 1 }} color="success.main" fontWeight={700} variant="h6">
                ${((orderDetails.subtotal || orderDetails.price || 0) + (orderDetails.shippingCost || 0)).toFixed(2)}
              </Typography>
            </Box>
            <Box>
              <Typography component="span" fontWeight={600} color="text.primary">Status:</Typography>
              <Chip
                sx={{ ml: 1 }}
                label={(orderDetails.status || '').charAt(0).toUpperCase() + (orderDetails.status || '').slice(1)}
                color={
                  orderDetails.status === 'delivered'
                    ? 'success'
                    : orderDetails.status === 'canceled'
                    ? 'error'
                    : 'warning'
                }
              />
            </Box>
            {orderDetails.status === 'canceled' && orderDetails.cancelReason && (
              <Box>
                <Typography component="span" fontWeight={600} color="text.primary">Cancel Reason:</Typography>
                <Typography component="span" sx={{ ml: 1 }} color="text.primary">
                  {orderDetails.cancelReason}
                </Typography>
              </Box>
            )}
          </Stack>
        </CardContent>
      </Card>

      {/* Order Items */}
      <Card>
        <CardContent>
          <Typography variant="h6" gutterBottom>Order Items</Typography>
          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>Product</TableCell>
                  <TableCell>Image</TableCell>
                  <TableCell>Product ID</TableCell>
                  <TableCell>Color</TableCell>
                  <TableCell>Size</TableCell>
                  <TableCell>Quantity</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {orderDetails.cartItems && orderDetails.cartItems.length > 0 ? (
                  orderDetails.cartItems.map((item, index) => {
                    // Get the product image from the correct path (merchandise product)
                    const productImage = item.product?.productImage;
                    const imageUrl = productImage ? 
                      `${productImage}` : 
                      null;
                    const productId = item.product?.productId || 'N/A';
                    const color = item.color || 'N/A';
                    const size = item.size || 'N/A';
                    return (
                      <TableRow key={index}>
                        <TableCell>{item.product?.productName || 'Unknown Product'}</TableCell>
                        <TableCell>
                          {imageUrl ? (
                            <Stack direction="row" spacing={1} alignItems="center">
                              <Box
                                component="img"
                                src={imageUrl}
                                alt={item.product.productName || 'Product Image'}
                                sx={{ width: 50, height: 50, objectFit: 'cover', borderRadius: 1, cursor: 'pointer' }}
                                onClick={() => imageUrl && handleImageClick(imageUrl)}
                              />
                              <Button
                                size="small"
                                variant="outlined"
                                onClick={() => imageUrl && handleImageClick(imageUrl)}
                                sx={{ minWidth: 'auto', px: 1 }}
                              >
                                View
                              </Button>
                            </Stack>
                          ) : (
                            <Box
                              sx={{
                                width: 50,
                                height: 50,
                                bgcolor: theme.palette.mode === 'dark' ? 'grey.700' : 'grey.200',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                borderRadius: 1
                              }}
                            >
                              <Typography variant="caption" color="text.secondary">
                                No Image
                              </Typography>
                            </Box>
                          )}
                        </TableCell>
                        <TableCell>{productId}</TableCell>
                        <TableCell>
                          {color && color !== 'N/A' ? (
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                              <Box
                                sx={{
                                  width: 20,
                                  height: 20,
                                  backgroundColor: color,
                                  borderRadius: '50%',
                                  border: theme.palette.mode === 'dark' ? '1px solid #4a5568' : '1px solid #ccc'
                                }}
                              />
                            </Box>
                          ) : (
                            'N/A'
                          )}
                        </TableCell>
                        <TableCell>{size}</TableCell>
                        <TableCell>{item.quantity || 1}</TableCell>
                      </TableRow>
                    );
                  })
                ) : (
                  <TableRow>
                    <TableCell colSpan={6} align="center">No items found</TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </TableContainer>
        </CardContent>
      </Card>

      {/* Cancel Dialog */}
      <Dialog
        open={isCancelReasonDialogOpen}
        onClose={handleCloseCancelDialog}
        maxWidth="sm"
        fullWidth
      >
        <DialogTitle>Cancel Order</DialogTitle>
        <DialogContent>
          <Box sx={{ mt: 2 }}>
            <FormControl fullWidth sx={{ mb: 2 }}>
              <InputLabel>Reason for Cancellation</InputLabel>
              <Select
                value={cancelReasonType}
                onChange={(e) => setCancelReasonType(e.target.value)}
                label="Reason for Cancellation"
              >
                {cancelReasons.map((reason) => (
                  <MenuItem key={reason} value={reason}>
                    {reason}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
            <TextField
              fullWidth
              label="Description (optional)"
              value={cancelReason}
              onChange={(e) => setCancelReason(e.target.value)}
              multiline
              rows={3}
              placeholder="Add more details about the cancellation..."
              sx={{ mt: 2 }}
            />
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseCancelDialog}>Cancel</Button>
          <Button
            onClick={handleAdminCancelConfirm}
            variant="contained"
            color="error"
            disabled={isLoading || !cancelReasonType || (cancelReasonType === 'Other' && !cancelReason)}
          >
            {isLoading ? 'Canceling...' : 'Admin Cancel Order'}
          </Button>
        </DialogActions>
      </Dialog>

      <Dialog open={isImageViewerOpen} onClose={handleCloseImageViewer} maxWidth="md" fullWidth>
        <DialogContent>
          {selectedImage && (
            <img src={selectedImage} alt="Enlarged product" style={{ width: '100%', height: 'auto' }} />
          )}
        </DialogContent>
      </Dialog>
    </Stack>
  );
};

export default OrderDetail;
