'use client'

import { useEffect, useState } from 'react'
import { useLocale, useTranslations } from 'next-intl'
import Grid from '@mui/material/Grid2'
import Menu from '@mui/material/Menu'
import MenuItem from '@mui/material/MenuItem'
import ListItemIcon from '@mui/material/ListItemIcon'
import Card from '@mui/material/Card'
import Stack from '@mui/material/Stack'
import Box from '@mui/material/Box'
import Typography from '@mui/material/Typography'
import Paper from '@mui/material/Paper'
import Chip from '@mui/material/Chip'
import IconButton from '@mui/material/IconButton'
import Tooltip from '@mui/material/Tooltip'
import Alert from '@mui/material/Alert'
import Button from '@mui/material/Button'
import Image from 'next/image'
import { toast } from 'react-toastify'

import { useGetOrderDetails } from '@/@core/hooks/data/orders/useGetOrderDetails'
import {
  type OrderItemInput,
  useCancelOrder,
  useOrderActions,
  useOrderLabels,
  useUpdateDeliveryFee,
  useUpdateOrderDiscount,
  useUpdateOrderEstimate,
  useUpdateOrderItems,
  useUpdateOrderNotes,
  useUpdateOrderPayment,
  useUpdateOrderStatus,
  useUpdateOrderTable,
  useUpdateOrderTax,
  useUpdateServiceFee
} from '@/@core/hooks/data/orders'
import { useGetTablesDropdown } from '@/@core/hooks/data/table'
import type { IOrder, IOrderCustomerAddress, ORDER_STATUS, PAYMENT_STATUS } from '@/types/data'
import { getErrorMessage, getSuccessMessage, type ApiResponse } from '@/utils/apiMessages'
import { SetSrc } from '@/utils/set-src'

import { SecondaryAction } from './order/orderConstants'
import OrderLoadingState from './order/OrderLoadingState'
import OrderHeader from './order/OrderHeader'
import OrderErrorState from './order/OrderErrorState'
import OrderNotesSection from './order/OrderNotesSection'
import OrderStatusDialog from './order/OrderStatusDialog'
import OrderPaymentDialog from './order/OrderPaymentDialog'
import OrderActionDialog from './order/OrderActionDialog'
import OrderItemsDrawer from './order/OrderItemsDrawer'
import { formatCurrency, formatDate } from './order/orderFormatters'

const OrderDetailsView = ({ orderId }: { orderId: string }) => {
  const t = useTranslations('ORDERS')
  const locale = useLocale()

  const { data, isLoading } = useGetOrderDetails(orderId, {
    enabled: Boolean(orderId)
  })

  const { data: tablesDropdown } = useGetTablesDropdown()

  const order = data?.data || null

  const { statusLabelMap, typeLabelMap, paymentLabelMap, resolveLocalizedLabel } = useOrderLabels(t, locale)
  const secondaryActions = useOrderActions(t)

  const getOrderStatusLabel = (target: IOrder) =>
    resolveLocalizedLabel(target.status_label_ar, target.status_label_en, statusLabelMap[target.status])

  const getOrderTypeLabel = (target: IOrder) =>
    resolveLocalizedLabel(target.type_label_ar, target.type_label_en, typeLabelMap[target.order_type])

  const getOrderPaymentLabel = (target: IOrder) =>
    resolveLocalizedLabel(target.payment_label_ar, target.payment_label_en, paymentLabelMap[target.payment_status])

  // Mutations
  const updateStatus = useUpdateOrderStatus()
  const updatePayment = useUpdateOrderPayment()
  const updateItems = useUpdateOrderItems()
  const updateDeliveryFee = useUpdateDeliveryFee()
  const updateServiceFee = useUpdateServiceFee()
  const updateTax = useUpdateOrderTax()
  const updateDiscount = useUpdateOrderDiscount()
  const updateNotes = useUpdateOrderNotes()
  const updateTable = useUpdateOrderTable()
  const updateEstimate = useUpdateOrderEstimate()
  const cancelOrder = useCancelOrder()

  // State
  const [statusDialogOpen, setStatusDialogOpen] = useState(false)
  const [paymentDialogOpen, setPaymentDialogOpen] = useState(false)
  const [itemsDrawerOpen, setItemsDrawerOpen] = useState(false)
  const [statusForm, setStatusForm] = useState<ORDER_STATUS>('pending')
  const [statusReason, setStatusReason] = useState('')
  const [paymentForm, setPaymentForm] = useState<PAYMENT_STATUS>('pending')
  const [paymentMethod, setPaymentMethod] = useState('')
  const [actionMenuAnchor, setActionMenuAnchor] = useState<null | HTMLElement>(null)
  const [activeAction, setActiveAction] = useState<SecondaryAction | null>(null)
  const [numericValue, setNumericValue] = useState('')
  const [taxRate, setTaxRate] = useState('')
  const [taxAmount, setTaxAmount] = useState('')
  const [notesValue, setNotesValue] = useState('')
  const [addressForm, setAddressForm] = useState<IOrderCustomerAddress>({})
  const [tableId, setTableId] = useState('')
  const [estimateForm, setEstimateForm] = useState<{ estimated_delivery_time: string; pickup_time: string }>({
    estimated_delivery_time: '',
    pickup_time: ''
  })
  const [cancelReason, setCancelReason] = useState('')

  useEffect(() => {
    if (order) {
      setStatusForm(order?.status)
      setPaymentForm(order?.payment_status)
      setPaymentMethod(order?.payment_method || 'cash')
      setNotesValue(order?.notes || '')
      setAddressForm(
        (order?.delivery_address as IOrderCustomerAddress) || {
          address_line: '',
          area: '',
          city: '',
          notes: ''
        }
      )
      setTableId(order?.table_id || '')
      setEstimateForm({
        estimated_delivery_time: order?.estimated_delivery_time || '',
        pickup_time: order?.pickup_time || ''
      })
      setNumericValue('')
      setTaxRate('')
      setTaxAmount('')
      setCancelReason('')
    }
  }, [order])

  const loadingAnyAction =
    updateDeliveryFee.isPending ||
    updateServiceFee.isPending ||
    updateTax.isPending ||
    updateDiscount.isPending ||
    updateNotes.isPending ||
    updateTable.isPending ||
    updateEstimate.isPending ||
    cancelOrder?.isPending

  const handleOpenAction = (action: SecondaryAction) => {
    if (!order) return
    setActiveAction(action)
    setActionMenuAnchor(null)

    switch (action) {
      case 'delivery_fee':
        setNumericValue(String(order?.delivery_fee ?? ''))
        break
      case 'service_fee':
        setNumericValue(String(order?.service_fee ?? ''))
        break
      case 'discount':
        setNumericValue(String(order?.discount_amount ?? ''))
        break
      case 'tax':
        setTaxRate('')
        setTaxAmount(String(order?.tax_amount ?? ''))
        break
      case 'notes':
        setNotesValue(order?.notes || '')
        break
      case 'address':
        setAddressForm(
          (order?.delivery_address as IOrderCustomerAddress) || {
            address_line: '',
            area: '',
            city: '',
            notes: ''
          }
        )
        break
      case 'table':
        setTableId(order?.table_id || '')
        break
      case 'estimate':
        // Set to now if no existing values, otherwise use order values
        setEstimateForm({
          estimated_delivery_time: order?.estimated_delivery_time || new Date().toISOString().slice(0, 16),
          pickup_time: order?.pickup_time || new Date().toISOString().slice(0, 16)
        })
        break
      case 'cancel':
        setCancelReason('')
        break
      default:
        break
    }
  }

  const closeActiveAction = () => setActiveAction(null)

  const handleStatusSubmit = async () => {
    if (!order) return
    try {
      const response = await updateStatus.mutateAsync({
        orderId: order?.id,
        status: statusForm,
        cancellation_reason: statusForm === 'cancelled' ? statusReason : undefined
      })
      toast.success(getSuccessMessage(response as ApiResponse, t('statusUpdated')))
      setStatusDialogOpen(false)
    } catch (error) {
      toast.error(getErrorMessage(error, t('statusUpdateError')))
    }
  }

  const handlePaymentSubmit = async () => {
    if (!order) return
    try {
      const response = await updatePayment.mutateAsync({
        orderId: order?.id,
        payment_status: paymentForm,
        payment_method: paymentMethod
      })
      toast.success(getSuccessMessage(response as ApiResponse, t('paymentUpdated')))
      setPaymentDialogOpen(false)
    } catch (error) {
      toast.error(getErrorMessage(error, t('paymentUpdateError')))
    }
  }

  const handleItemsSubmit = async (items: OrderItemInput[]) => {
    if (!order) return
    try {
      const response = await updateItems.mutateAsync({
        orderId: order?.id,
        items
      })
      toast.success(getSuccessMessage(response as ApiResponse, t('itemsDrawer.success')))
      setItemsDrawerOpen(false)
    } catch (error) {
      toast.error(getErrorMessage(error, t('itemsDrawer.error')))
    }
  }

  const handleActionSubmit = async () => {
    if (!order || !activeAction) return
    try {
      let response: ApiResponse<IOrder> | undefined

      switch (activeAction) {
        case 'delivery_fee':
          response = await updateDeliveryFee.mutateAsync({ orderId: order?.id, value: Number(numericValue) })
          break
        case 'service_fee':
          response = await updateServiceFee.mutateAsync({ orderId: order?.id, value: Number(numericValue) })
          break
        case 'discount':
          response = await updateDiscount.mutateAsync({ orderId: order?.id, value: Number(numericValue) })
          break
        case 'tax':
          response = await updateTax.mutateAsync({
            orderId: order?.id,
            tax_rate: taxRate ? Number(taxRate) : undefined,
            tax_amount: taxAmount ? Number(taxAmount) : undefined
          })
          break
        case 'notes':
          response = await updateNotes.mutateAsync({ orderId: order?.id, notes: notesValue })
          break
        case 'table':
          response = await updateTable.mutateAsync({ orderId: order?.id, table_id: tableId })
          break
        case 'estimate':
          response = await updateEstimate.mutateAsync({ orderId: order?.id, ...estimateForm })
          break
        case 'cancel':
          response = await cancelOrder?.mutateAsync({ orderId: order?.id, cancellation_reason: cancelReason })
          break
        default:
          break
      }
      toast.success(getSuccessMessage(response, t('actionSuccess')))
      closeActiveAction()
    } catch (error) {
      toast.error(getErrorMessage(error, t('actionError')))
    }
  }

  const disableActionSubmit =
    loadingAnyAction ||
    (activeAction === 'cancel' && !cancelReason.trim()) ||
    ((activeAction === 'delivery_fee' || activeAction === 'service_fee' || activeAction === 'discount') &&
      numericValue === '')

  if (isLoading) {
    return <OrderLoadingState t={t} />
  }

  if (!order) {
    return <OrderErrorState t={t} />
  }

  return (
    <>
      <Grid container spacing={3}>
        {/* Header Section */}
        <OrderHeader
          order={order}
          t={t}
          locale={locale}
          getOrderStatusLabel={getOrderStatusLabel}
          getOrderPaymentLabel={getOrderPaymentLabel}
          getOrderTypeLabel={getOrderTypeLabel}
          onStatusClick={() => setStatusDialogOpen(true)}
          onPaymentClick={() => setPaymentDialogOpen(true)}
          onMoreActionsClick={event => setActionMenuAnchor(event.currentTarget)}
        />

        {/* Info Cards Row */}
        {/* Customer Info Card */}
        <Grid size={{ xs: 12, md: 4 }}>
          <Card
            sx={{
              height: '100%',
              p: 3,
              background:
                'linear-gradient(135deg, rgba(var(--mui-palette-primary-mainChannel) / 0.08) 0%, rgba(var(--mui-palette-primary-mainChannel) / 0.02) 100%)',
              border: '1px solid',
              borderColor: 'primary.lighter',
              position: 'relative',
              overflow: 'hidden',
              '&::before': {
                content: '""',
                position: 'absolute',
                top: -20,
                insetInlineEnd: -20,
                width: 100,
                height: 100,
                borderRadius: '50%',
                bgcolor: 'primary.lighter',
                opacity: 0.3
              }
            }}
          >
            <Box sx={{ position: 'relative', zIndex: 1 }}>
              <Stack direction='row' spacing={2} alignItems='flex-start' mb={3}>
                <Box
                  sx={{
                    width: 56,
                    height: 56,
                    borderRadius: 3,
                    background:
                      'linear-gradient(135deg, var(--mui-palette-primary-main) 0%, var(--mui-palette-primary-dark) 100%)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    boxShadow: '0 4px 12px rgba(var(--mui-palette-primary-mainChannel) / 0.3)',
                    flexShrink: 0
                  }}
                >
                  <i className='tabler-user text-2xl text-white' />
                </Box>
                <Box flex={1}>
                  <Typography variant='overline' color='text.secondary' sx={{ fontSize: '1rem', fontWeight: 700 }}>
                    {t('customer')}
                  </Typography>
                  <Typography variant='h5' fontWeight={700} sx={{ mt: 0.5, lineHeight: 1.3 }}>
                    {order?.customer_name}
                  </Typography>
                </Box>
              </Stack>

              <Stack spacing={2}>
                <Box
                  sx={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 1.5,
                    p: 2,
                    borderRadius: 2,
                    bgcolor: 'background.paper',
                    border: '1px solid',
                    borderColor: 'divider',
                    transition: 'all 0.2s',
                    '&:hover': {
                      borderColor: 'primary.main',
                      boxShadow: '0 2px 8px rgba(var(--mui-palette-primary-mainChannel) / 0.12)'
                    }
                  }}
                >
                  <Box
                    sx={{
                      width: 36,
                      height: 36,
                      borderRadius: 2,
                      bgcolor: 'success.lighter',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      flexShrink: 0
                    }}
                  >
                    <i className='tabler-phone text-lg' style={{ color: 'var(--mui-palette-success-main)' }} />
                  </Box>
                  <Box flex={1} dir='ltr' sx={{ textAlign: 'left' }}>
                    <Typography variant='body2' color='text.secondary' sx={{ fontWeight: 600 }}>
                      {t('phone')}
                    </Typography>
                    <Typography variant='body1' fontWeight={600} sx={{ mt: 0.25 }}>
                      {order?.customer_phone}
                    </Typography>
                  </Box>
                  <Tooltip title={t('copyPhone')}>
                    <IconButton
                      size='small'
                      onClick={() => {
                        navigator.clipboard.writeText(order?.customer_phone || '')
                        toast.success(t('copied'))
                      }}
                      sx={{ opacity: 0.6, '&:hover': { opacity: 1 } }}
                    >
                      <i className='tabler-copy text-base' />
                    </IconButton>
                  </Tooltip>
                </Box>

                {order?.customer_email && (
                  <Box
                    sx={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: 1.5,
                      p: 2,
                      borderRadius: 2,
                      bgcolor: 'background.paper',
                      border: '1px solid',
                      borderColor: 'divider',
                      transition: 'all 0.2s',
                      '&:hover': {
                        borderColor: 'info.main',
                        boxShadow: '0 2px 8px rgba(var(--mui-palette-info-mainChannel) / 0.12)'
                      }
                    }}
                  >
                    <Box
                      sx={{
                        width: 36,
                        height: 36,
                        borderRadius: 2,
                        bgcolor: 'info.lighter',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        flexShrink: 0
                      }}
                    >
                      <i className='tabler-mail text-lg' style={{ color: 'var(--mui-palette-info-main)' }} />
                    </Box>
                    <Box flex={1}>
                      <Typography variant='body2' color='text.secondary' sx={{ fontWeight: 600 }}>
                        {t('email')}
                      </Typography>
                      <Typography variant='body1' fontWeight={600} sx={{ mt: 0.25, wordBreak: 'break-word' }}>
                        {order?.customer_email}
                      </Typography>
                    </Box>
                    <Tooltip title={t('copyEmail')}>
                      <IconButton
                        size='small'
                        onClick={() => {
                          navigator.clipboard.writeText(order?.customer_email || '')
                          toast.success(t('copied'))
                        }}
                        sx={{ opacity: 0.6, '&:hover': { opacity: 1 } }}
                      >
                        <i className='tabler-copy text-base' />
                      </IconButton>
                    </Tooltip>
                  </Box>
                )}
              </Stack>
            </Box>
          </Card>
        </Grid>

        {/* Fulfillment Info Card */}
        <Grid size={{ xs: 12, md: 4 }}>
          <Card
            sx={{
              height: '100%',
              p: 3,
              background:
                'linear-gradient(135deg, rgba(var(--mui-palette-info-mainChannel) / 0.08) 0%, rgba(var(--mui-palette-info-mainChannel) / 0.02) 100%)',
              border: '1px solid',
              borderColor: 'info.lighter',
              position: 'relative',
              overflow: 'hidden',
              '&::before': {
                content: '""',
                position: 'absolute',
                top: -20,
                insetInlineEnd: -20,
                width: 100,
                height: 100,
                borderRadius: '50%',
                bgcolor: 'info.lighter',
                opacity: 0.3
              }
            }}
          >
            <Box sx={{ position: 'relative', zIndex: 1 }}>
              <Stack direction='row' spacing={2} alignItems='center' mb={3}>
                <Box
                  sx={{
                    width: 56,
                    height: 56,
                    borderRadius: 3,
                    background:
                      'linear-gradient(135deg, var(--mui-palette-info-main) 0%, var(--mui-palette-info-dark) 100%)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    boxShadow: '0 4px 12px rgba(var(--mui-palette-info-mainChannel) / 0.3)',
                    flexShrink: 0
                  }}
                >
                  <i className='tabler-map-pin text-2xl text-white' />
                </Box>
                <Box flex={1} display='flex' flexDirection='column'>
                  <Typography variant='overline' color='text.secondary' sx={{ fontSize: '1rem', fontWeight: 700 }}>
                    {t('fulfillment')}
                  </Typography>
                  <Chip
                    size='medium'
                    icon={
                      <i
                        className={`tabler-${order?.order_type === 'dine_in' ? 'armchair' : order?.order_type === 'takeaway' ? 'shopping-bag' : 'bike'}`}
                      />
                    }
                    label={typeLabelMap[order?.order_type]}
                    color={
                      order?.order_type === 'dine_in'
                        ? 'primary'
                        : order?.order_type === 'takeaway'
                          ? 'secondary'
                          : 'info'
                    }
                    sx={{ mt: 1, fontWeight: 600 }}
                  />
                </Box>
              </Stack>

              <Stack spacing={2}>
                {order?.table ? (
                  <Box
                    sx={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: 1.5,
                      p: 2,
                      borderRadius: 2,
                      bgcolor: 'background.paper',
                      border: '1px solid',
                      borderColor: 'divider',
                      transition: 'all 0.2s',
                      '&:hover': {
                        borderColor: 'primary.main',
                        boxShadow: '0 2px 8px rgba(var(--mui-palette-primary-mainChannel) / 0.12)'
                      }
                    }}
                  >
                    <Box
                      sx={{
                        width: 36,
                        height: 36,
                        borderRadius: 2,
                        bgcolor: 'primary.lighter',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        flexShrink: 0
                      }}
                    >
                      <i className='tabler-desk text-2xl' style={{ color: 'var(--mui-palette-primary-main)' }} />
                    </Box>
                    <Box flex={1}>
                      <Typography variant='body2' color='text.secondary' sx={{ fontWeight: 600 }}>
                        {t('tableNumber')}
                      </Typography>
                      <Typography variant='body1' fontWeight={600} sx={{ mt: 0.25 }}>
                        {t('table', { table: order?.table.table_number })}
                      </Typography>
                    </Box>
                  </Box>
                ) : order?.delivery_address ? (
                  <Box
                    sx={{
                      display: 'flex',
                      alignItems: 'flex-start',
                      gap: 1.5,
                      p: 2,
                      borderRadius: 2,
                      bgcolor: 'background.paper',
                      border: '1px solid',
                      borderColor: 'divider',
                      transition: 'all 0.2s',
                      '&:hover': {
                        borderColor: 'info.main',
                        boxShadow: '0 2px 8px rgba(var(--mui-palette-info-mainChannel) / 0.12)'
                      }
                    }}
                  >
                    <Box
                      sx={{
                        width: 36,
                        height: 36,
                        borderRadius: 2,
                        bgcolor: 'info.lighter',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        flexShrink: 0
                      }}
                    >
                      <i className='tabler-map-pin text-2xl' style={{ color: 'var(--mui-palette-info-main)' }} />
                    </Box>
                    <Box flex={1}>
                      <Typography variant='body2' color='text.secondary' sx={{ fontWeight: 600 }}>
                        {t('deliveryAddress')}
                      </Typography>
                      <Typography variant='body1' fontWeight={600} sx={{ mt: 0.25 }}>
                        {(order?.delivery_address as IOrderCustomerAddress)?.address_line}
                      </Typography>
                      <Typography variant='body2' color='text.secondary' sx={{ mt: 0.5, display: 'block' }}>
                        {(order?.delivery_address as IOrderCustomerAddress)?.city},{' '}
                        {(order?.delivery_address as IOrderCustomerAddress)?.area}
                      </Typography>
                    </Box>
                    <Tooltip title={t('openInMaps')}>
                      <IconButton
                        size='small'
                        onClick={() => {
                          const address = `${(order?.delivery_address as IOrderCustomerAddress)?.address_line}, ${(order?.delivery_address as IOrderCustomerAddress)?.city}`
                          window.open(
                            `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(address)}`,
                            '_blank'
                          )
                        }}
                        sx={{ opacity: 0.6, '&:hover': { opacity: 1 } }}
                      >
                        <i className='tabler-map-2 text-base' />
                      </IconButton>
                    </Tooltip>
                  </Box>
                ) : (
                  <Alert severity='info' icon={<i className='tabler-info-circle' />} sx={{ fontSize: '0.875rem' }}>
                    {t('noFulfillment')}
                  </Alert>
                )}

                {order?.estimated_delivery_time && (
                  <Box
                    sx={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: 1.5,
                      p: 2,
                      borderRadius: 2,
                      bgcolor: 'background.paper',
                      border: '1px solid',
                      borderColor: 'divider'
                    }}
                  >
                    <Box
                      sx={{
                        width: 36,
                        height: 36,
                        borderRadius: 2,
                        bgcolor: 'warning.lighter',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        flexShrink: 0
                      }}
                    >
                      <i
                        className='tabler-truck-delivery text-2xl'
                        style={{ color: 'var(--mui-palette-warning-main)' }}
                      />
                    </Box>
                    <Box flex={1}>
                      <Typography variant='body2' color='text.secondary' sx={{ fontWeight: 600 }}>
                        {t('estimatedDelivery')}
                      </Typography>
                      <Typography variant='body1' fontWeight={600} sx={{ mt: 0.25 }}>
                        {formatDate(order?.estimated_delivery_time, locale)}
                      </Typography>
                    </Box>
                  </Box>
                )}

                {order?.pickup_time && (
                  <Box
                    sx={{
                      display: 'flex',
                      alignItems: 'center',
                      gap: 1.5,
                      p: 2,
                      borderRadius: 2,
                      bgcolor: 'background.paper',
                      border: '1px solid',
                      borderColor: 'divider'
                    }}
                  >
                    <Box
                      sx={{
                        width: 36,
                        height: 36,
                        borderRadius: 2,
                        bgcolor: 'secondary.lighter',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        flexShrink: 0
                      }}
                    >
                      <i className='tabler-clock text-2xl' style={{ color: 'var(--mui-palette-secondary-main)' }} />
                    </Box>
                    <Box flex={1}>
                      <Typography variant='body2' color='text.secondary' sx={{ fontWeight: 600 }}>
                        {t('pickupTime')}
                      </Typography>
                      <Typography variant='body1' fontWeight={600} sx={{ mt: 0.25 }}>
                        {formatDate(order?.pickup_time, locale)}
                      </Typography>
                    </Box>
                  </Box>
                )}
              </Stack>
            </Box>
          </Card>
        </Grid>

        {/* Financial Card */}
        <Grid size={{ xs: 12, md: 4 }}>
          <Card
            sx={{
              height: '100%',
              p: 3,
              background:
                'linear-gradient(135deg, rgba(var(--mui-palette-success-mainChannel) / 0.08) 0%, rgba(var(--mui-palette-success-mainChannel) / 0.02) 100%)',
              border: '1px solid',
              borderColor: 'success.lighter',
              position: 'relative',
              overflow: 'hidden',
              '&::before': {
                content: '""',
                position: 'absolute',
                top: -20,
                insetInlineEnd: -20,
                width: 100,
                height: 100,
                borderRadius: '50%',
                bgcolor: 'success.lighter',
                opacity: 0.3
              }
            }}
          >
            <Box sx={{ position: 'relative', zIndex: 1 }}>
              <Stack direction='row' spacing={2} alignItems='flex-start' mb={3}>
                <Box
                  sx={{
                    width: 56,
                    height: 56,
                    borderRadius: 3,
                    background:
                      'linear-gradient(135deg, var(--mui-palette-success-main) 0%, var(--mui-palette-success-dark) 100%)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    boxShadow: '0 4px 12px rgba(var(--mui-palette-success-mainChannel) / 0.3)',
                    flexShrink: 0
                  }}
                >
                  <i className='tabler-coin text-2xl text-white' />
                </Box>
                <Box flex={1}>
                  <Typography
                    variant='overline'
                    color='text.secondary'
                    sx={{ fontSize: '1rem', fontWeight: 700, letterSpacing: 1 }}
                  >
                    {t('financial')}
                  </Typography>
                  <Typography variant='h5' fontWeight={800} color='success.main' sx={{ mt: 0.5, lineHeight: 1 }}>
                    {formatCurrency(order?.total_amount, order?.currency_symbol)}
                  </Typography>
                </Box>
              </Stack>

              <Stack spacing={1.5}>
                {/* Subtotal */}
                <Box
                  sx={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    p: 2,
                    borderRadius: 2,
                    bgcolor: 'background.paper',
                    border: '1px solid',
                    borderColor: 'divider'
                  }}
                >
                  <Stack direction='row' spacing={1} alignItems='center'>
                    <Box
                      sx={{
                        width: 28,
                        height: 28,
                        borderRadius: 1.5,
                        bgcolor: 'action.hover',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                      }}
                    >
                      <i className='tabler-receipt text-sm' />
                    </Box>
                    <Typography variant='body1' fontWeight={500}>
                      {t('subtotal')}
                    </Typography>
                  </Stack>
                  <Typography variant='body1' fontWeight={600}>
                    {formatCurrency(order?.subtotal, order?.currency_symbol)}
                  </Typography>
                </Box>

                {/* Tax */}
                <Box
                  sx={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    p: 2,
                    borderRadius: 2,
                    bgcolor: 'background.paper',
                    border: '1px solid',
                    borderColor: 'divider'
                  }}
                >
                  <Stack direction='row' spacing={1} alignItems='center'>
                    <Box
                      sx={{
                        width: 28,
                        height: 28,
                        borderRadius: 1.5,
                        bgcolor: 'warning.lighter',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                      }}
                    >
                      <i className='tabler-percentage text-sm' style={{ color: 'var(--mui-palette-warning-main)' }} />
                    </Box>
                    <Typography variant='body1' fontWeight={500}>
                      {t('tax')}
                    </Typography>
                  </Stack>
                  <Typography variant='body1' fontWeight={600}>
                    {formatCurrency(order?.tax_amount, order?.currency_symbol)}
                  </Typography>
                </Box>

                {/* Delivery Fee */}
                <Box
                  sx={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    p: 2,
                    borderRadius: 2,
                    bgcolor: 'background.paper',
                    border: '1px solid',
                    borderColor: 'divider'
                  }}
                >
                  <Stack direction='row' spacing={1} alignItems='center'>
                    <Box
                      sx={{
                        width: 28,
                        height: 28,
                        borderRadius: 1.5,
                        bgcolor: 'info.lighter',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                      }}
                    >
                      <i className='tabler-truck-delivery text-sm' style={{ color: 'var(--mui-palette-info-main)' }} />
                    </Box>
                    <Typography variant='body1' fontWeight={500}>
                      {t('deliveryFee')}
                    </Typography>
                  </Stack>
                  <Typography variant='body1' fontWeight={600}>
                    {formatCurrency(order?.delivery_fee, order?.currency_symbol)}
                  </Typography>
                </Box>

                {/* Service Fee */}
                {order?.service_fee ? (
                  <Box
                    sx={{
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                      p: 2,
                      borderRadius: 2,
                      bgcolor: 'background.paper',
                      border: '1px solid',
                      borderColor: 'divider'
                    }}
                  >
                    <Stack direction='row' spacing={1} alignItems='center'>
                      <Box
                        sx={{
                          width: 28,
                          height: 28,
                          borderRadius: 1.5,
                          bgcolor: 'secondary.lighter',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center'
                        }}
                      >
                        <i
                          className='tabler-receipt-2 text-sm'
                          style={{ color: 'var(--mui-palette-secondary-main)' }}
                        />
                      </Box>
                      <Typography variant='body1' fontWeight={500}>
                        {t('serviceFee')}
                      </Typography>
                    </Stack>
                    <Typography variant='body1' fontWeight={600}>
                      {formatCurrency(order?.service_fee, order?.currency_symbol)}
                    </Typography>
                  </Box>
                ) : null}

                {/* Discount */}
                {order?.discount_amount ? (
                  <Box
                    sx={{
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'space-between',
                      p: 2,
                      borderRadius: 2,
                      bgcolor: 'error.lighter',
                      border: '1px solid',
                      borderColor: 'error.main'
                    }}
                  >
                    <Stack direction='row' spacing={1} alignItems='center'>
                      <Box
                        sx={{
                          width: 28,
                          height: 28,
                          borderRadius: 1.5,
                          bgcolor: 'error.main',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center'
                        }}
                      >
                        <i className='tabler-ticket text-sm text-white' />
                      </Box>
                      <Typography variant='body1' fontWeight={600} color='error.main'>
                        {t('discount')}
                      </Typography>
                    </Stack>
                    <Typography variant='body1' fontWeight={700} color='error.main'>
                      -{formatCurrency(order?.discount_amount, order?.currency_symbol)}
                    </Typography>
                  </Box>
                ) : null}

                {/* Total */}
                <Box
                  sx={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    p: 2,
                    borderRadius: 2,
                    bgcolor: 'success.main',
                    mt: 1,
                    boxShadow: '0 4px 12px rgba(var(--mui-palette-success-mainChannel) / 0.3)'
                  }}
                >
                  <Stack direction='row' spacing={1} alignItems='center'>
                    <Box
                      sx={{
                        width: 32,
                        height: 32,
                        borderRadius: 2,
                        bgcolor: 'rgba(255,255,255,0.2)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                      }}
                    >
                      <i className='tabler-cash text-lg text-white' />
                    </Box>
                    <Typography variant='h6' fontWeight={700} sx={{ color: 'white' }}>
                      {t('total')}
                    </Typography>
                  </Stack>
                  <Typography variant='h5' fontWeight={800} sx={{ color: 'white' }}>
                    {formatCurrency(order?.total_amount, order?.currency_symbol)}
                  </Typography>
                </Box>
              </Stack>
            </Box>
          </Card>
        </Grid>

        {/* Items Section */}
        <Grid size={{ xs: 12 }}>
          <Card
            sx={{
              p: 3,
              background:
                'linear-gradient(135deg, rgba(var(--mui-palette-secondary-mainChannel) / 0.05) 0%, rgba(var(--mui-palette-secondary-mainChannel) / 0.01) 100%)',
              border: '1px solid',
              borderColor: 'divider'
            }}
          >
            <Stack direction='row' justifyContent='space-between' alignItems='center' mb={3} flexWrap='wrap' gap={2}>
              <Stack direction='row' spacing={2} alignItems='center'>
                <Box
                  sx={{
                    width: 48,
                    height: 48,
                    borderRadius: 2,
                    background:
                      'linear-gradient(135deg, var(--mui-palette-primary-main) 0%, var(--mui-palette-primary-dark) 100%)',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    boxShadow: '0 4px 12px rgba(var(--mui-palette-primary-mainChannel) / 0.3)'
                  }}
                >
                  <i className='tabler-shopping-bag text-xl text-white' />
                </Box>
                <Box>
                  <Typography variant='h6' fontWeight={700}>
                    {t('items')}
                  </Typography>
                  <Typography variant='caption' color='text.secondary' fontWeight={600}>
                    {t('itemsCount', { count: order?.items.length })}
                  </Typography>
                </Box>
              </Stack>
              <Button
                variant='contained'
                color='primary'
                onClick={() => setItemsDrawerOpen(true)}
                startIcon={<i className='tabler-edit' />}
                sx={{ boxShadow: 2 }}
              >
                {t('editItems')}
              </Button>
            </Stack>

            <Stack spacing={2}>
              {order?.items?.map((item, idx) => (
                <Paper
                  key={item?.id}
                  elevation={0}
                  sx={{
                    p: 2.5,
                    borderRadius: 2,
                    border: '1px solid',
                    borderColor: 'divider',
                    transition: 'all 0.2s',
                    '&:hover': {
                      borderColor: 'primary.main',
                      boxShadow: '0 4px 12px rgba(var(--mui-palette-primary-mainChannel) / 0.12)',
                      transform: 'translateY(-2px)'
                    }
                  }}
                >
                  <Grid container spacing={2} alignItems='center'>
                    {/* Product Image */}
                    <Grid size={{ xs: 12, sm: 'auto' }}>
                      <Box
                        sx={{
                          width: 80,
                          height: 80,
                          borderRadius: 2,
                          overflow: 'hidden',
                          position: 'relative',
                          border: '2px solid',
                          borderColor: 'primary.lighter',
                          bgcolor: 'background.paper',
                          flexShrink: 0
                        }}
                      >
                        <Image
                          src={item?.product?.image ? SetSrc(item?.product?.image) : '/images/thumbnail.jpg'}
                          alt={item?.product_name_en}
                          fill
                          className='object-cover'
                          onError={e => {
                            const target = e.target as HTMLImageElement
                            target.src = '/images/thumbnail.jpg'
                          }}
                          sizes='80px'
                          priority={idx < 3}
                        />
                      </Box>
                    </Grid>

                    {/* Product Details */}
                    <Grid size={{ xs: 12 }}>
                      <Stack spacing={1}>
                        <Typography variant='subtitle1' fontWeight={700} sx={{ lineHeight: 1.3 }}>
                          {locale === 'ar' ? item.product_name_ar : item?.product_name_en}
                        </Typography>

                        {item.selected_variations && item.selected_variations.length > 0 && (
                          <Stack direction='row' spacing={0.5} flexWrap='wrap' gap={0.5}>
                            {item.selected_variations.map((variation, vIdx) => (
                              <Chip
                                key={vIdx}
                                label={typeof variation === 'string' ? variation : variation?.name_en}
                                size='small'
                                variant='outlined'
                                color='primary'
                                sx={{ height: 22, fontSize: '0.7rem', fontWeight: 600, borderStyle: 'dashed' }}
                              />
                            ))}
                          </Stack>
                        )}

                        {item.special_instructions && (
                          <Box
                            sx={{
                              display: 'flex',
                              gap: 1,
                              alignItems: 'flex-start',
                              p: 1,
                              borderRadius: 1.5,
                              bgcolor: 'warning.lighter',
                              border: '1px solid',
                              borderColor: 'warning.main'
                            }}
                          >
                            <i
                              className='tabler-note text-base'
                              style={{ color: 'var(--mui-palette-warning-dark)', marginTop: 1, flexShrink: 0 }}
                            />
                            <Typography
                              variant='caption'
                              color='warning.dark'
                              fontWeight={600}
                              sx={{ fontStyle: 'italic', lineHeight: 1.4 }}
                            >
                              {item.special_instructions}
                            </Typography>
                          </Box>
                        )}
                      </Stack>
                    </Grid>

                    {/* Quantity, Price, Total */}
                    <Grid size={{ xs: 12, sm: 'auto' }}>
                      <Stack direction='row' spacing={2} justifyContent='space-between' sx={{ minWidth: { sm: 300 } }}>
                        {/* Quantity */}
                        <Box sx={{ textAlign: 'center', flex: 1 }}>
                          <Typography
                            variant='caption'
                            color='text.secondary'
                            fontWeight={700}
                            sx={{
                              display: 'block',
                              mb: 1,
                              textTransform: 'uppercase',
                              fontSize: '0.65rem',
                              letterSpacing: 0.5
                            }}
                          >
                            {t('quantity')}
                          </Typography>
                          <Chip
                            label={item.quantity}
                            size='medium'
                            color='primary'
                            sx={{ fontWeight: 700, minWidth: 70, fontSize: '0.875rem' }}
                          />
                        </Box>

                        {/* Unit Price */}
                        <Box sx={{ textAlign: 'center', flex: 1 }}>
                          <Typography
                            variant='caption'
                            color='text.secondary'
                            fontWeight={700}
                            sx={{
                              display: 'block',
                              mb: 1,
                              textTransform: 'uppercase',
                              fontSize: '0.65rem',
                              letterSpacing: 0.5
                            }}
                          >
                            {t('price')}
                          </Typography>
                          <Typography variant='body1' fontWeight={700} color='text.primary'>
                            {formatCurrency(item.unit_price, order?.currency_symbol)}
                          </Typography>
                        </Box>

                        {/* Total Price */}
                        <Box sx={{ textAlign: 'center', flex: 1 }}>
                          <Typography
                            variant='caption'
                            color='text.secondary'
                            fontWeight={700}
                            sx={{
                              display: 'block',
                              mb: 1,
                              textTransform: 'uppercase',
                              fontSize: '0.65rem',
                              letterSpacing: 0.5
                            }}
                          >
                            {t('total')}
                          </Typography>
                          <Box
                            sx={{
                              display: 'inline-flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              px: 1.5,
                              py: 0.75,
                              borderRadius: 1.5,
                              bgcolor: 'success.main',
                              boxShadow: '0 2px 8px rgba(var(--mui-palette-success-mainChannel) / 0.3)'
                            }}
                          >
                            <Typography variant='body1' fontWeight={800} sx={{ color: 'white' }}>
                              {formatCurrency(item.total_price, order?.currency_symbol)}
                            </Typography>
                          </Box>
                        </Box>
                      </Stack>
                    </Grid>
                  </Grid>
                </Paper>
              ))}
            </Stack>

            {/* Summary Footer */}
            <Box
              sx={{
                mt: 3,
                p: 2.5,
                borderRadius: 2,
                background:
                  'linear-gradient(135deg, rgba(var(--mui-palette-primary-mainChannel) / 0.08) 0%, rgba(var(--mui-palette-primary-mainChannel) / 0.02) 100%)',
                border: '2px dashed',
                borderColor: 'primary.main'
              }}
            >
              <Stack direction='row' justifyContent='space-between' alignItems='center' flexWrap='wrap' gap={2}>
                <Stack direction='row' spacing={1.5} alignItems='center'>
                  <Box
                    sx={{
                      width: 40,
                      height: 40,
                      borderRadius: 2,
                      background:
                        'linear-gradient(135deg, var(--mui-palette-primary-main) 0%, var(--mui-palette-primary-dark) 100%)',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      boxShadow: '0 4px 12px rgba(var(--mui-palette-primary-mainChannel) / 0.3)'
                    }}
                  >
                    <i className='tabler-sum text-lg text-white' />
                  </Box>
                  <Typography variant='h6' fontWeight={700}>
                    {t('itemsSubtotal')}
                  </Typography>
                </Stack>
                <Typography variant='h5' fontWeight={800} color='primary.main'>
                  {formatCurrency(order?.subtotal, order?.currency_symbol)}
                </Typography>
              </Stack>
            </Box>
          </Card>
        </Grid>

        {/* Notes Section */}
        <OrderNotesSection order={order} t={t} />
      </Grid>

      {/* Action Menu */}
      <Menu anchorEl={actionMenuAnchor} open={Boolean(actionMenuAnchor)} onClose={() => setActionMenuAnchor(null)}>
        {secondaryActions.map(action => (
          <MenuItem key={action.key} onClick={() => handleOpenAction(action.key)}>
            <ListItemIcon>
              <i className={action.icon} />
            </ListItemIcon>
            {action.label}
          </MenuItem>
        ))}
      </Menu>

      {/* Dialogs */}
      <OrderStatusDialog
        open={statusDialogOpen}
        onClose={() => setStatusDialogOpen(false)}
        t={t}
        statusForm={statusForm}
        setStatusForm={setStatusForm}
        statusReason={statusReason}
        setStatusReason={setStatusReason}
        onSubmit={handleStatusSubmit}
        loading={updateStatus.isPending}
        statusLabelMap={statusLabelMap}
      />

      <OrderPaymentDialog
        open={paymentDialogOpen}
        onClose={() => setPaymentDialogOpen(false)}
        t={t}
        paymentForm={paymentForm}
        setPaymentForm={setPaymentForm}
        paymentMethod={paymentMethod}
        setPaymentMethod={setPaymentMethod}
        onSubmit={handlePaymentSubmit}
        loading={updatePayment.isPending}
        paymentLabelMap={paymentLabelMap}
      />

      <OrderActionDialog
        open={Boolean(activeAction)}
        onClose={closeActiveAction}
        action={activeAction}
        t={t}
        onSubmit={handleActionSubmit}
        loading={loadingAnyAction}
        disabled={disableActionSubmit}
        numericValue={numericValue}
        setNumericValue={setNumericValue}
        taxRate={taxRate}
        setTaxRate={setTaxRate}
        taxAmount={taxAmount}
        setTaxAmount={setTaxAmount}
        notesValue={notesValue}
        setNotesValue={setNotesValue}
        addressForm={addressForm}
        setAddressForm={setAddressForm}
        tableId={tableId}
        setTableId={setTableId}
        tablesDropdown={tablesDropdown?.data}
        estimateForm={estimateForm}
        setEstimateForm={setEstimateForm}
        cancelReason={cancelReason}
        setCancelReason={setCancelReason}
      />

      <OrderItemsDrawer
        open={itemsDrawerOpen}
        onClose={() => setItemsDrawerOpen(false)}
        order={order}
        onSubmit={handleItemsSubmit}
        loading={updateItems.isPending}
      />
    </>
  )
}

export default OrderDetailsView
