'use client';

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import dayjs, { Dayjs } from 'dayjs';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
import { Calendar, CalendarProps, dayjsLocalizer, View, Views } from 'react-big-calendar';

import 'react-big-calendar/lib/css/react-big-calendar.css';

import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { fetchEvents } from '@/services/events.service';
import { getAllOrders, updateOrderStatus, adminCancelOrder, exportOrdersToCSV, fetchOrdersByUser } from '@/services/order.service';
import { GetApp as ExportIcon } from '@mui/icons-material';
import CalendarMonthIcon from '@mui/icons-material/CalendarMonth';
import ReorderIcon from '@mui/icons-material/Reorder';
import SearchIcon from '@mui/icons-material/Search';
import TuneIcon from '@mui/icons-material/Tune';
import VisibilityIcon from '@mui/icons-material/Visibility';
import CancelIcon from '@mui/icons-material/Cancel';
import {
  Box,
  Button,
  ButtonGroup,
  Chip,
  CircularProgress,
  Drawer,
  FormControl,
  IconButton,
  InputAdornment,
  InputLabel,
  OutlinedInput,
  Stack,
  Typography,
  useTheme,
  Tabs,
  Tab,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  MenuItem,
  Select,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  TablePagination,
} from '@mui/material';
import { DatePicker } from '@mui/x-date-pickers';
import { enqueueSnackbar } from 'notistack';
import { useSnackbar } from 'notistack';

import { IOrder } from '@/types/order.type';
import CalendarComponent from '@/components/dashboard/events/calendar';
// import AddEventModal from './addEventModal';
import { CustomTable } from '@/components/dashboard/table';

dayjs.extend(utc);
dayjs.extend(timezone);

// Day.js Localizer
const localizer = dayjsLocalizer(dayjs);

type Event = {
  id: number;
  title: string;
  start: Date;
  end: Date;
  eventUsersCount: number;
};

const tableColumns = [
  {
    title: 'Order ID',
    width: 130,
    isSort: true,
    key: 'cartData.cartRandomId',
  },
  {
    title: 'Username',
    width: 100,
    isSort: true,
    key: 'userData.fullName',
  },
  {
    title: 'Email',
    width: 180,
    isSort: true,
    key: 'userData.emailAddress',
  },
  {
    title: 'Phone',
    width: 200,
    isSort: true,
    key: 'userData.phoneNumber',
  },
  {
    title: 'Price',
    width: 150,
    isSort: true,
    key: 'price',
  },
  {
    title: 'Status',
    width: 200,
    isSort: true,
    key: 'status',
  },
  {
    title: 'Last Update',
    width: 200,
    isSort: true,
    key: 'updatedAt',
  },
  {
    title: 'Actions',
    width: 50,
    isSort: false,
    key: 'actions',
  },
];

type OrderTab = 'new' | 'delivered' | 'canceled';

const isValidOrderTab = (tab: string | null): tab is OrderTab =>
  tab === 'new' || tab === 'delivered' || tab === 'canceled';

interface OrdersProps {
  userId?: string; // Make userId optional
}

const Orders: React.FC<OrdersProps> = ({ userId }) => {
  const [myEvents, setEvents] = useState<Event[]>([]);
  const [currentDate, setCurrentDate] = useState<Date>(new Date());
  const [currentView, setCurrentView] = useState<View>('month');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [orders, setOrders] = useState<IOrder[]>([]);
  const [total, setTotal] = useState(0);
  const [search, setSearch] = useState<string>('');
  const [rowsPerPage, setRowsPerPage] = useState<number>(10);
  const [page, setPage] = useState<number>(0);
  const [order, setOrder] = useState<'asc' | 'desc'>('desc');
  const [orderBy, setOrderBy] = useState<string>('createdAt');
  const [refreshSelectedOrganizations, setRefreshSelectedOrganizations] = useState<boolean>(false);
  const [open, setOpen] = React.useState(false);
  const [view, setView] = React.useState<'list' | 'calendar'>('calendar');
  const [eventType, setEventType] = React.useState<'upcoming' | 'completed'>('upcoming');

  const [selectedDate, setSelectedDate] = useState<Dayjs | null | undefined>(dayjs(new Date()));
  const router = useRouter();
  const searchParams = useSearchParams();
  const pathname = usePathname();

  const [currentTab, setCurrentTab] = useState<OrderTab>(() => {
    const tab = searchParams.get('tab');
    return isValidOrderTab(tab) ? tab : 'new';
  });
  const [cancelDialogOpen, setCancelDialogOpen] = useState(false);
  const [selectedOrderId, setSelectedOrderId] = useState<string | null>(null);
  const [selectedOrder, setSelectedOrder] = useState<IOrder | null>(null);
  const [isCancelReasonDialogOpen, setIsCancelReasonDialogOpen] = useState(false);
  const [cancelReason, setCancelReason] = useState('');
  const [cancelReasonType, setCancelReasonType] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isCancelLoading, setIsCancelLoading] = useState(false);

  const cancelReasons = [
    'Out of stock',
    'Customer request',
    'Invalid address',
    'Payment issue',
    'Other'
  ];

  const { enqueueSnackbar } = useSnackbar();

  useEffect(() => {
    const param = searchParams.get('event_modal');

    // Open the modal if the "modal" parameter is present
    if (param) {
      setIsModalOpen(true);
    } else {
      setIsModalOpen(false);
    }
  }, [searchParams]);

  useEffect(() => {
    const tab = searchParams.get('tab');
    if (isValidOrderTab(tab)) {
      setCurrentTab(tab);
      return;
    }

    if (!userId) {
      const params = new URLSearchParams(searchParams.toString());
      params.set('tab', 'new');
      router.replace(`${pathname}?${params.toString()}`, { scroll: false });
    }

    setCurrentTab('new');
  }, [searchParams, pathname, router, userId]);

  useEffect(() => {
    if (userId) {
      fetchOrders(userId);
    } else {
      fetchOrders();
    }
  }, [page, rowsPerPage, search, order, orderBy, currentTab, userId]);

  const openModal = () => {
    router.replace(`?event_modal=1`); // Add a `modal` query param to the route
  };
  const closeSlotModal = () => {
    setIsModalOpen(false);
    // Remove the `modal` query param while preserving dynamic path
    const currentParams = new URLSearchParams(searchParams);
    currentParams.delete('event_modal');

    const newUrl = `${pathname}${currentParams.toString() ? `?${currentParams}` : ''}`;
    router.replace(newUrl); // Remove the `modal` query param from the route
  };

  const theme = useTheme(); // Get the MUI theme
  const primaryColor = theme.palette.primary.main; // Access the primary color
  // Handle change of the selected date
  const handleDateChange = (date: Dayjs | null) => {
    setSelectedDate(date);
    if (date) {
      setCurrentDate(date.toDate());
    }
  };

  const handleSelectEvent = useCallback((event: Event) => {
    window.alert(`Event: ${event.title}`);
  }, []);

  const handleNavigate = useCallback((date: Date) => {
    setCurrentDate(date);
  }, []);

  const handleViewChange = useCallback((view: View) => {
    setCurrentView(view);
    if (view === 'month') {
      setCurrentDate(new Date()); // Reset to current month if month view is selected
    }
  }, []);

  const handleYearChange = useCallback((yearChange: number) => {
    setCurrentDate((prev) => {
      const newDate = dayjs(prev).add(yearChange, 'year');
      return newDate.toDate();
    });
  }, []);

  const { defaultDate, scrollToTime } = useMemo(
    () => ({
      defaultDate: new Date(),
      scrollToTime: new Date(1970, 1, 1, 6),
    }),
    []
  );

  const eventStyleGetter = useCallback(
    (event: Event) => {
      // Apply the primary color to the event background
      let backgroundColor = primaryColor; // Default to primary color

      if (event.title.toLowerCase().includes('project')) {
        backgroundColor = '#e91e63'; // Override background color for Project events
      } else if (event.title.toLowerCase().includes('meeting')) {
        backgroundColor = '#4caf50'; // Override background color for Meeting events
      }

      return {
        style: {
          backgroundColor, // Use primaryColor from MUI theme
          color: '#000', // Optional: change text color to white
        },
      };
    },
    [primaryColor] // Make sure to memoize with primaryColor
  );

  const handleTabChange = (_event: React.SyntheticEvent, newValue: OrderTab) => {
    setCurrentTab(newValue);
    setPage(0);

    if (!userId) {
      const params = new URLSearchParams(searchParams.toString());
      params.set('tab', newValue);
      router.replace(`${pathname}?${params.toString()}`, { scroll: false });
    }
  };

  const handleCancelClick = (order: IOrder) => {
    setSelectedOrder(order);
    setIsCancelReasonDialogOpen(true);
  };

  const handleViewDetails = (order: IOrder) => {
    router.push(`/dashboard/orders/${order._id}`);
  };

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

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

      const response = await adminCancelOrder(selectedOrder._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('');
        setSelectedOrder(null);
        
        // Switch to canceled tab first
        setCurrentTab('canceled');
        
        // Then refresh the orders list
        await fetchOrders();
      } 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 {
      setIsCancelLoading(false);
    }
  };

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

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

      const response = await updateOrderStatus(selectedOrder._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('');
        setSelectedOrder(null);
        
        // Switch to canceled tab first
        setCurrentTab('canceled');
        
        // Then refresh the orders list
        await fetchOrders();
      } 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 {
      setIsCancelLoading(false);
    }
  };

  const handleCloseCancelReasonDialog = () => {
    setIsCancelReasonDialogOpen(false);
    setCancelReason('');
    setCancelReasonType('');
    setSelectedOrder(null);
  };

  const fetchOrders = async (currentUserId?: string) => {
    try {
      setIsLoading(true);
      console.log('Fetching orders with status:', currentTab);
      const response = currentUserId
        ? await fetchOrdersByUser(currentUserId, {
            offset: page * rowsPerPage,
            limit: rowsPerPage,
            search: search,
            sort: order,
            sortField: orderBy,
            status: currentTab || undefined,
          })
        : await getAllOrders({
            offset: page * rowsPerPage,
            limit: rowsPerPage,
            search: search,
            sort: order,
            sortField: orderBy,
            status: currentTab || undefined,
          });
      console.log('Orders response:', response);
      // Check if we have valid data in the response
      if (response?.data?.data) {
        const ordersData = response.data.data;
        console.log('Orders data:', ordersData);
        // Map the orders to ensure they have the required fields
        const mappedOrders = ordersData.map((order: any) => ({
          ...order,
          cartRandomId: order.cartRandomId || order._id,
          userName: order.userName || order.userData?.fullName || 'N/A',
          totalAmount: order.totalAmount || order.price || 0,
          status: order.status, // Do not default to 'processing'
          createdAt: order.createdAt || order.created_at || new Date().toISOString()
        }));
        console.log('Mapped orders:', mappedOrders);
        setOrders(mappedOrders);
        setTotal(response.data.total || mappedOrders.length);
      } else {
        console.error('Invalid response format:', response);
        setOrders([]);
        setTotal(0);
      }
    } catch (error) {
      console.error('Error fetching orders:', error);
      enqueueSnackbar('Failed to fetch orders', { variant: 'error' });
      setOrders([]);
      setTotal(0);
    } finally {
      setIsLoading(false);
    }
  };

  const changeOrderStatus = async (id: string, newStatus: string) => {
    try {
      setIsLoading(true);
      console.log('Changing order status:', { id, newStatus });
      const response = await updateOrderStatus(id, { status: newStatus });
      console.log('Status change response:', response?.data);
      
      if (response?.status === 200 || response?.data?.status === 200) {
        enqueueSnackbar(`Order marked as ${newStatus}`, { variant: 'success' });
        // Wait a moment before refreshing to ensure backend has updated
        setTimeout(async () => {
          await fetchOrders();
        }, 1000);
      } 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);
    }
  };

  const handlePageChange = (event: unknown, newPage: number) => {
    setPage(newPage);
  };

  const handleRowsPerPageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const handleSort = (property: string) => {
    const isAsc = orderBy === property && order === 'asc';
    setOrder(isAsc ? 'desc' : 'asc');
    setOrderBy(property);
  };

  const handleSelected = (selected: string[]) => {
    // setSelectedOrganizations(selected);

    setRefreshSelectedOrganizations(false);
  };

  const handleAdminCancelClick = (order: IOrder) => {
    setSelectedOrder(order);
    setIsCancelReasonDialogOpen(true);
  };

  const actions = [
    {
      icon: <VisibilityIcon />,
      label: 'View Details',
      onClick: (order: IOrder) => handleViewDetails(order),
    },
  ];

  const adminActions = [
    {
      icon: <VisibilityIcon />,
      label: 'View Details',
      onClick: (order: IOrder) => handleViewDetails(order),
    },
    {
      icon: <CancelIcon />,
      label: 'Admin Cancel',
      onClick: (order: IOrder) => handleAdminCancelClick(order),
      condition: (order: IOrder) => order.status === 'processing' || order.status === 'new',
    },
  ];

  const handleExport = () => {
    if (orders.length > 0) {
      exportOrdersToCSV(orders);
      enqueueSnackbar('Orders exported successfully', { variant: 'success' });
    } else {
      enqueueSnackbar('No orders to export', { variant: 'warning' });
    }
  };

  return (
    <Box sx={{ minHeight: '100vh', p: 3 }}>
      {/* Modern Header Section */}
      <Paper
        elevation={0}
        sx={{
          p: 3,
          mb: 3,
          borderRadius: 4,
          background: '#FFDD31',
          color: '#0B0504',
        }}
      >
        <Stack direction="row" justifyContent="space-between" alignItems="center">
          <Box>
            <Typography variant="h4" fontWeight={700} gutterBottom>
              Orders Management
            </Typography>
            <Typography variant="body1" sx={{ opacity: 0.9 }}>
              Track and manage customer orders across all statuses
            </Typography>
          </Box>
          <Stack direction="row" spacing={2} alignItems="center">
            <Button
              variant="contained"
              startIcon={<ExportIcon />}
              onClick={handleExport}
              disabled={orders.length === 0}
              sx={{
                bgcolor: 'rgba(11, 5, 4, 0.8)',
                color: '#FFDD31',
                borderRadius: 2,
                textTransform: 'none',
                fontWeight: 600,
                minWidth: 120,
                border: '1px solid rgba(11, 5, 4, 0.9)',
                '&:hover': {
                  bgcolor: 'rgba(11, 5, 4, 0.9)',
                  transform: 'translateY(-1px)',
                },
                '&:disabled': {
                  bgcolor: 'rgba(11, 5, 4, 0.4)',
                  color: 'rgba(255, 221, 49, 0.5)',
                  border: '1px solid rgba(11, 5, 4, 0.4)',
                },
                transition: 'all 0.3s ease',
              }}
            >
              Export CSV
            </Button>
            <FormControl sx={{ minWidth: 300 }}>
              <OutlinedInput
                placeholder="Search orders, customers..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                sx={{
                  bgcolor: 'rgba(255, 255, 255, 0.15)',
                  color: 'white',
                  '& .MuiOutlinedInput-notchedOutline': {
                    borderColor: 'rgba(255, 255, 255, 0.3)',
                  },
                  '&:hover .MuiOutlinedInput-notchedOutline': {
                    borderColor: 'rgba(255, 255, 255, 0.5)',
                  },
                  '&.Mui-focused .MuiOutlinedInput-notchedOutline': {
                    borderColor: 'rgba(255, 255, 255, 0.8)',
                  },
                  '& input::placeholder': {
                    color: 'rgba(255, 255, 255, 0.7)',
                    opacity: 1,
                  },
                }}
                endAdornment={
                  <InputAdornment position="end">
                    <IconButton edge="end" sx={{ color: 'rgba(11, 5, 4, 0.8)' }}>
                      <SearchIcon />
                    </IconButton>
                  </InputAdornment>
                }
              />
            </FormControl>
          </Stack>
        </Stack>
      </Paper>

      {/* Modern Tab Navigation */}
      <Paper
        elevation={0}
        sx={{
          mb: 3,
          borderRadius: 4,
          background: theme.palette.mode === 'dark' 
            ? 'linear-gradient(145deg, #1a202c 0%, #2d3748 100%)' 
            : 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
          border: theme.palette.mode === 'dark' 
            ? '1px solid #4a5568' 
            : '1px solid rgba(255, 255, 255, 0.2)',
          boxShadow: theme.palette.mode === 'dark' 
            ? '0 8px 32px rgba(0, 0, 0, 0.3)' 
            : '0 8px 32px rgba(0, 0, 0, 0.08)',
        }}
      >
        <Tabs 
          value={currentTab} 
          onChange={handleTabChange}
          sx={{
            '& .MuiTabs-indicator': {
              height: 3,
              borderRadius: '3px 3px 0 0',
              background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
            },
            '& .MuiTab-root': {
              textTransform: 'none',
              fontWeight: 600,
              paddingLeft: 3,
              fontSize: '1rem',
              py: 2,
              px: 3,
              color: theme.palette.mode === 'dark' ? '#e2e8f0' : 'inherit',
              '&.Mui-selected': {
                color: theme.palette.mode === 'dark' ? '#667eea' : '#667eea',
              }
            }
          }}
        >
          <Tab 
            label={
              <Stack direction="row" alignItems="center" spacing={1}>
                <Typography>New Orders</Typography>
                {/* <Chip 
                  label={orders.filter(o => o.status === 'new').length} 
                  size="small" 
                  color="warning"
                  sx={{ minWidth: 24, height: 20 }}
                /> */}
              </Stack>
            } 
            value="new" 
          />
          <Tab 
            label={
              <Stack direction="row" alignItems="center" spacing={1}>
                <Typography>Delivered</Typography>
                {/* <Chip 
                  label={orders.filter(o => o.status === 'delivered').length} 
                  size="small" 
                  color="success"
                  sx={{ minWidth: 24, height: 20 }}
                /> */}
              </Stack>
            } 
            value="delivered" 
          />
          <Tab 
            label={
              <Stack direction="row" alignItems="center" spacing={1}>
                <Typography>Canceled</Typography>
                {/* <Chip 
                  label={orders.filter(o => o.status === 'canceled').length} 
                  size="small" 
                  color="error"
                  sx={{ minWidth: 24, height: 20 }}
                /> */}
              </Stack>
            } 
            value="canceled" 
          />
        </Tabs>
      </Paper>

      {/* Modern Table Container */}
      <Paper
        elevation={0}
        sx={{
          borderRadius: 4,
          background: theme.palette.mode === 'dark' 
            ? 'linear-gradient(145deg, #1a202c 0%, #2d3748 100%)' 
            : 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
          border: theme.palette.mode === 'dark' 
            ? '1px solid #4a5568' 
            : '1px solid rgba(255, 255, 255, 0.2)',
          boxShadow: theme.palette.mode === 'dark' 
            ? '0 8px 32px rgba(0, 0, 0, 0.3)' 
            : '0 8px 32px rgba(0, 0, 0, 0.08)',
          overflow: 'hidden',
          position: 'relative',
        }}
      >
        {isLoading && (
          <Box
            sx={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              backgroundColor: theme.palette.mode === 'dark' 
                ? 'rgba(26, 32, 44, 0.8)' 
                : 'rgba(255, 255, 255, 0.8)',
              zIndex: 1,
              backdropFilter: 'blur(4px)',
            }}
          >
            <Stack alignItems="center" spacing={2}>
              <CircularProgress size={40} thickness={4} />
              <Typography variant="body2" color="text.secondary">
                Loading orders...
              </Typography>
            </Stack>
          </Box>
        )}
        <TableContainer>
          <Table>
            <TableHead>
              <TableRow
                sx={{
                  '& .MuiTableCell-head': {
                    backgroundColor: theme.palette.mode === 'dark' ? '#2d3748' : '#f8fafc',
                    fontWeight: 600,
                    color: theme.palette.mode === 'dark' ? '#e2e8f0' : '#374151',
                    borderBottom: theme.palette.mode === 'dark' ? '2px solid #4a5568' : '2px solid #e5e7eb',
                    py: 2,
                  }
                }}
              >
                <TableCell>Order ID</TableCell>
                <TableCell>Customer</TableCell>
                <TableCell>Date</TableCell>
                <TableCell>Subtotal</TableCell>
                <TableCell>Shipping</TableCell>
                <TableCell>Total</TableCell>
                <TableCell>Status</TableCell>
                <TableCell align="center">Actions</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {Array.isArray(orders) && orders.length > 0 ? (
                orders.map((order, index) => (
                  <TableRow 
                    key={order._id}
                    sx={{
                      '&:hover': {
                        backgroundColor: theme.palette.mode === 'dark' ? '#2d3748' : '#f8fafc',
                        transform: 'scale(1.001)',
                        transition: 'all 0.2s ease-in-out',
                      },
                      '& .MuiTableCell-root': {
                        borderBottom: theme.palette.mode === 'dark' ? '1px solid #4a5568' : '1px solid #f1f5f9',
                        py: 2,
                        color: theme.palette.mode === 'dark' ? 'text.primary' : 'inherit',
                      }
                    }}
                  >
                    <TableCell>
                      <Typography variant="body2" fontWeight={600} color="primary.main">
                        #{order.cartRandomId || order._id.slice(-8)}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Stack>
                        <Typography variant="body2" fontWeight={500} color="text.primary">
                          {order.userName || 'N/A'}
                        </Typography>
                        <Typography variant="caption" color="text.secondary">
                          {order.userData?.emailAddress || 'No email'}
                        </Typography>
                      </Stack>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" color="text.primary">
                        {order.createdAt ? new Date(order.createdAt).toLocaleDateString('en-US', {
                          month: 'short',
                          day: 'numeric',
                          year: 'numeric'
                        }) : '-'}
                      </Typography>
                      <Typography variant="caption" color="text.secondary">
                        {order.createdAt ? new Date(order.createdAt).toLocaleTimeString('en-US', {
                          hour: '2-digit',
                          minute: '2-digit'
                        }) : '-'}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" fontWeight={600} color="text.primary">
                        ${(order.subtotal || order.price || 0).toFixed(2)}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" fontWeight={500} color="text.secondary">
                        ${(order.shippingCost || 0).toFixed(2)}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Typography variant="body2" fontWeight={600} color="success.main">
                        ${((order.subtotal || order.price || 0) + (order.shippingCost || 0)).toFixed(2)}
                      </Typography>
                    </TableCell>
                    <TableCell>
                      <Chip
                        label={(order.status || '').charAt(0).toUpperCase() + (order.status || '').slice(1)}
                        color={
                          order.status === 'delivered'
                            ? 'success'
                            : order.status === 'canceled'
                            ? 'error'
                            : 'warning'
                        }
                        variant="filled"
                        size="small"
                        sx={{
                          fontWeight: 600,
                          minWidth: 80,
                          '&.MuiChip-colorSuccess': {
                            backgroundColor: theme.palette.mode === 'dark' ? '#065f46' : '#dcfce7',
                            color: theme.palette.mode === 'dark' ? '#6ee7b7' : '#166534',
                          },
                          '&.MuiChip-colorError': {
                            backgroundColor: theme.palette.mode === 'dark' ? '#7f1d1d' : '#fef2f2',
                            color: theme.palette.mode === 'dark' ? '#fca5a5' : '#dc2626',
                          },
                          '&.MuiChip-colorWarning': {
                            backgroundColor: theme.palette.mode === 'dark' ? '#92400e' : '#fef3c7',
                            color: theme.palette.mode === 'dark' ? '#fbbf24' : '#d97706',
                          },
                        }}
                      />
                    </TableCell>
                    <TableCell align="center">
                      <Stack direction="row" spacing={1} justifyContent="center">
                        {adminActions
                          .filter(action => !action.condition || action.condition(order))
                          .map((action, actionIndex) => (
                            <IconButton
                              key={actionIndex}
                              size="small"
                              onClick={() => action.onClick(order)}
                              title={action.label}
                              sx={{
                                color: action.label === 'Admin Cancel' ? 'error.main' : 'primary.main',
                                '&:hover': {
                                  backgroundColor: action.label === 'Admin Cancel' 
                                    ? 'error.50' 
                                    : 'primary.50',
                                  transform: 'scale(1.1)',
                                },
                                transition: 'all 0.2s ease-in-out',
                              }}
                            >
                              {action.icon}
                            </IconButton>
                          ))}
                      </Stack>
                    </TableCell>
                  </TableRow>
                ))
              ) : (
                <TableRow>
                  <TableCell colSpan={6} align="center" sx={{ py: 3 }}>
                    <Stack alignItems="center" spacing={1}>
                      <Box
                        sx={{
                          width: 40,
                          height: 40,
                          borderRadius: '50%',
                          backgroundColor: theme.palette.mode === 'dark' ? '#4a5568' : '#f3f4f6',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                        }}
                      >
                        <ReorderIcon sx={{ fontSize: 20, color: theme.palette.mode === 'dark' ? '#a0aec0' : '#9ca3af' }} />
                      </Box>
                      <Typography variant="body1" color="text.secondary">
                        No orders found
                      </Typography>
                    </Stack>
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </TableContainer>
        
        {/* Modern Pagination */}
        <Box sx={{ p: 2, borderTop: theme.palette.mode === 'dark' ? '1px solid #4a5568' : '1px solid #f1f5f9' }}>
          <TablePagination
            component="div"
            count={total}
            page={page}
            onPageChange={handlePageChange}
            rowsPerPage={rowsPerPage}
            onRowsPerPageChange={handleRowsPerPageChange}
            sx={{
              '& .MuiTablePagination-toolbar': {
                px: 0,
              },
              '& .MuiTablePagination-selectLabel, & .MuiTablePagination-displayedRows': {
                fontWeight: 500,
                color: theme.palette.mode === 'dark' ? '#a0aec0' : '#6b7280',
              },
              '& .MuiIconButton-root': {
                color: theme.palette.mode === 'dark' ? '#a0aec0' : '#6b7280',
                '&:hover': {
                  backgroundColor: theme.palette.mode === 'dark' ? '#4a5568' : '#f3f4f6',
                },
                '&.Mui-disabled': {
                  color: theme.palette.mode === 'dark' ? '#718096' : '#d1d5db',
                },
              },
            }}
          />
        </Box>
      </Paper>

      <Dialog
        open={isCancelReasonDialogOpen}
        onClose={handleCloseCancelReasonDialog}
        maxWidth="sm"
        fullWidth
        PaperProps={{
          sx: {
            borderRadius: 4,
            background: theme.palette.mode === 'dark' 
              ? 'linear-gradient(145deg, #1a202c 0%, #2d3748 100%)' 
              : 'linear-gradient(145deg, #ffffff 0%, #f8fafc 100%)',
            border: theme.palette.mode === 'dark' 
              ? '1px solid rgba(255, 255, 255, 0.12)' 
              : '1px solid rgba(0, 0, 0, 0.12)',
            boxShadow: theme.palette.mode === 'dark' 
              ? '0 24px 48px rgba(0, 0, 0, 0.4), 0 8px 16px rgba(0, 0, 0, 0.2)' 
              : '0 24px 48px rgba(0, 0, 0, 0.15), 0 8px 16px rgba(0, 0, 0, 0.1)',
            backdropFilter: 'blur(20px)',
          }
        }}
        BackdropProps={{
          sx: {
            backdropFilter: 'blur(12px)',
            backgroundColor: theme.palette.mode === 'dark' 
              ? 'rgba(0, 0, 0, 0.7)' 
              : 'rgba(0, 0, 0, 0.5)',
          }
        }}
      >
        <DialogTitle
          sx={{
            background: theme.palette.mode === 'dark' 
              ? 'linear-gradient(135deg, #ffd700 0%, #ffed4a 100%)' 
              : 'linear-gradient(135deg, #1a202c 0%, #2d3748 100%)',
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
            backgroundClip: 'text',
            fontWeight: 700,
            fontSize: '1.5rem',
            letterSpacing: '-0.025em',
            pb: 1,
          }}
        >
          {selectedOrder?.status === 'canceled' ? '📋 Order Cancellation Details' : '⚠️ Cancel Order'}
        </DialogTitle>
        <DialogContent>
          <Stack spacing={2} sx={{ mt: 2 }}>
            {selectedOrder?.status === 'canceled' ? (
              <>
                <Typography variant="subtitle1">
                  Order ID: {selectedOrder?.cartRandomId || selectedOrder?._id}
                </Typography>
                <Typography variant="subtitle1">
                  Customer: {selectedOrder?.userName || 'N/A'}
                </Typography>
                <Typography variant="subtitle1">
                  Amount: ${selectedOrder?.totalAmount?.toFixed(2) || '0.00'}
                </Typography>
                <Typography variant="subtitle1">
                  Cancellation Reason: {selectedOrder?.cancelReason || 'No reason provided'}
                </Typography>
              </>
            ) : (
              <>
                <FormControl fullWidth>
                  <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 }}
                />
              </>
            )}
          </Stack>
        </DialogContent>
        <DialogActions sx={{ p: 3, gap: 2, borderTop: theme.palette.mode === 'dark' ? '1px solid #4a5568' : '1px solid #e2e8f0' }}>
          <Button 
            onClick={handleCloseCancelReasonDialog}
            size="large"
            sx={{
              minWidth: 100,
              height: 44,
              borderRadius: 3,
              border: theme.palette.mode === 'dark' ? '2px solid #4a5568' : '2px solid #e2e8f0',
              color: theme.palette.mode === 'dark' ? '#a0aec0' : '#64748b',
              fontWeight: 500,
              textTransform: 'none',
              fontSize: '1rem',
              '&:hover': {
                border: theme.palette.mode === 'dark' ? '2px solid #718096' : '2px solid #cbd5e0',
                backgroundColor: theme.palette.mode === 'dark' 
                  ? 'rgba(113, 128, 150, 0.1)' 
                  : 'rgba(203, 213, 224, 0.1)',
                transform: 'translateY(-1px)',
              },
              transition: 'all 0.2s ease-in-out',
            }}
          >
            {selectedOrder?.status === 'canceled' ? 'Close' : 'Cancel'}
          </Button>
          {selectedOrder?.status !== 'canceled' && (
            <Button 
              onClick={handleAdminCancelConfirm}
              variant="contained" 
              disabled={isCancelLoading || !cancelReasonType}
              size="large"
              sx={{
                minWidth: 140,
                height: 44,
                borderRadius: 3,
                background: 'linear-gradient(135deg, #dc2626 0%, #b91c1c 100%)',
                color: '#ffffff',
                fontWeight: 600,
                textTransform: 'none',
                fontSize: '1rem',
                '&:hover': {
                  background: 'linear-gradient(135deg, #b91c1c 0%, #991b1b 100%)',
                  transform: 'translateY(-2px)',
                  boxShadow: '0 8px 25px rgba(220, 38, 38, 0.3)',
                },
                '&:disabled': {
                  background: theme.palette.mode === 'dark' ? '#4a5568' : '#e2e8f0',
                  color: theme.palette.mode === 'dark' ? '#a0aec0' : '#9ca3af',
                },
                transition: 'all 0.2s ease-in-out',
                boxShadow: '0 4px 12px rgba(220, 38, 38, 0.2)',
              }}
            >
              {isCancelLoading ? 'Canceling...' : '🚫 Admin Cancel Order'}
            </Button>
          )}
          {selectedOrder?.status === 'canceled' && (
            <Button 
              variant="contained" 
              onClick={() => {
                handleCloseCancelReasonDialog();
                router.push(`/dashboard/orders/${selectedOrder?._id}`);
              }}
            >
              View Full Details
            </Button>
          )}
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default Orders;
