'use client'

import { useCallback, useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { useRouter, useSearchParams } from 'next/navigation'
import { useLocale, useTranslations } from 'next-intl'
import Card from '@mui/material/Card'
import Grid from '@mui/material/Grid2'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Chip from '@mui/material/Chip'
import type { ChipProps } from '@mui/material/Chip'
import Stack from '@mui/material/Stack'
import Divider from '@mui/material/Divider'
import MenuItem from '@mui/material/MenuItem'
import IconButton from '@mui/material/IconButton'
import Tooltip from '@mui/material/Tooltip'
import Dialog from '@mui/material/Dialog'
import DialogTitle from '@mui/material/DialogTitle'
import DialogContent from '@mui/material/DialogContent'
import DialogActions from '@mui/material/DialogActions'
import CircularProgress from '@mui/material/CircularProgress'
import Alert from '@mui/material/Alert'
import Box from '@mui/material/Box'
import {
  createColumnHelper,
  flexRender,
  getCoreRowModel,
  useReactTable,
  type ColumnDef,
  type FilterFn
} from '@tanstack/react-table'
import { toast } from 'react-toastify'

import CustomTextField from '@core/components/mui/TextField'
import tableStyles from '@core/styles/table.module.css'
import CustomTablePaginationComponent from '@/components/CustomTablePaginationComponent'
import {
  useGetOrdersList,
  useGetOrdersStatistics,
  useUpdateOrderPayment,
  useUpdateOrderStatus
} from '@/@core/hooks/data/orders'
import type { IOrder, ORDER_STATUS, ORDER_TYPE, PAYMENT_STATUS } from '@/types/data'
import type { OrdersSortField } from '@/@core/hooks/data/orders/useGetOrders'
import type { TPageSizeOption } from '@/@core/types/api'
import AppReactDatepicker from '@/@core/styles/AppReactDatepicker'
import { getErrorMessage, getSuccessMessage, type ApiResponse } from '@/utils/apiMessages'

type StatusFilterValue = ORDER_STATUS | 'all'

const statusChipMeta: Record<ORDER_STATUS, { color: ChipProps['color']; icon: string }> = {
  pending: { color: 'warning', icon: 'tabler-clock' },
  confirmed: { color: 'info', icon: 'tabler-check' },
  preparing: { color: 'info', icon: 'tabler-chef-hat' },
  ready: { color: 'success', icon: 'tabler-bell' },
  delivered: { color: 'success', icon: 'tabler-truck' },
  completed: { color: 'secondary', icon: 'tabler-confetti' },
  cancelled: { color: 'error', icon: 'tabler-ban' }
}

const typeChipMeta: Record<ORDER_TYPE, { color: ChipProps['color']; icon: string }> = {
  dine_in: { color: 'primary', icon: 'tabler-armchair' },
  takeaway: { color: 'secondary', icon: 'tabler-shopping-bag' },
  delivery: { color: 'info', icon: 'tabler-bike' }
}

const paymentChipMeta: Record<PAYMENT_STATUS, { color: ChipProps['color']; icon: string }> = {
  pending: { color: 'warning', icon: 'tabler-clock-dollar' },
  paid: { color: 'success', icon: 'tabler-cash' },
  failed: { color: 'error', icon: 'tabler-alert-triangle' },
  refunded: { color: 'info', icon: 'tabler-rotate' }
}

const columnHelper = createColumnHelper<IOrder>()
const noopFilter: FilterFn<IOrder> = () => true

const OrdersView = () => {
  const router = useRouter()
  const searchParams = useSearchParams()
  const locale = useLocale()
  const t = useTranslations('ORDERS')
  const searchParamsString = searchParams.toString()

  const page = Number(searchParams.get('page')) || 1
  const perPage = (Number(searchParams.get('per_page')) as TPageSizeOption) || 10
  const sortField = (searchParams.get('sort_by') as OrdersSortField) || 'created_at'
  const sortDirection = (searchParams.get('sort_as') as 'asc' | 'desc') || 'desc'
  const statusFilter = (searchParams.get('status') as ORDER_STATUS | null) ?? 'all'
  const orderTypeFilter = (searchParams.get('order_type') as ORDER_TYPE | null) || undefined

  const [searchValue, setSearchValue] = useState(searchParams.get('search') || '')
  const [orderLookup, setOrderLookup] = useState('')
  const [statusDialog, setStatusDialog] = useState<{ open: boolean; order?: IOrder | null }>({
    open: false,
    order: null
  })
  const [paymentDialog, setPaymentDialog] = useState<{ open: boolean; order?: IOrder | null }>({
    open: false,
    order: null
  })
  const [statusForm, setStatusForm] = useState<ORDER_STATUS>('pending')
  const [statusReason, setStatusReason] = useState('')
  const [paymentStatusForm, setPaymentStatusForm] = useState<PAYMENT_STATUS>('pending')
  const [paymentMethod, setPaymentMethod] = useState('')
  const [fromDateValue, setFromDateValue] = useState<Date | null>(
    searchParams.get('date_from') ? new Date(searchParams.get('date_from') as string) : null
  )
  const [toDateValue, setToDateValue] = useState<Date | null>(
    searchParams.get('date_to') ? new Date(searchParams.get('date_to') as string) : null
  )
  const [orderTypeSelect, setOrderTypeSelect] = useState<ORDER_TYPE | ''>(orderTypeFilter || '')
  const [paymentStatusSelect, setPaymentStatusSelect] = useState<PAYMENT_STATUS | ''>(
    (searchParams.get('payment_status') as PAYMENT_STATUS | null) || ''
  )
  const [isMobile, setIsMobile] = useState(false)

  const { data: ordersResponse, isLoading } = useGetOrdersList({
    page,
    per_page: perPage,
    search: searchParams.get('search') || undefined,
    status: statusFilter === 'all' ? undefined : statusFilter,
    payment_status: (searchParams.get('payment_status') as PAYMENT_STATUS) || undefined,
    order_type: orderTypeFilter,
    date_from: searchParams.get('date_from') || undefined,
    date_to: searchParams.get('date_to') || undefined,
    sort_by: sortField,
    sort_as: sortDirection,
    with_relations: 1
  })

  const { data: stats, isLoading: statsLoading } = useGetOrdersStatistics({})
  const statsData = stats?.data
  const todayStats = statsData?.today
  const monthStats = statsData?.this_month

  const updateStatus = useUpdateOrderStatus()
  const updatePayment = useUpdateOrderPayment()
  // const findOrder = useFindOrderByNumber()

  const rows = ordersResponse?.data?.data || []
  const total = ordersResponse?.data?.total || 0

  // Calculate active filters count
  const activeFiltersCount = [
    searchParams.get('search'),
    statusFilter !== 'all' ? statusFilter : null,
    orderTypeFilter,
    paymentStatusSelect,
    fromDateValue,
    toDateValue
  ].filter(Boolean).length

  const statusLabelMap = useMemo(
    () =>
      ({
        pending: t('statusFilters.pending'),
        confirmed: t('statusFilters.confirmed'),
        preparing: t('statusFilters.preparing'),
        ready: t('statusFilters.ready'),
        delivered: t('statusFilters.delivered'),
        completed: t('statusFilters.completed'),
        cancelled: t('statusFilters.cancelled')
      }) as Record<ORDER_STATUS, string>,
    [t]
  )

  const typeLabelMap = useMemo(
    () =>
      ({
        dine_in: t('dineIn'),
        delivery: t('delivery'),
        takeaway: t('takeaway')
      }) as Record<ORDER_TYPE, string>,
    [t]
  )

  const getLocalizedStatusLabel = (order: IOrder) => {
    const localized = locale === 'ar' ? order.status_label_ar : order.status_label_en

    return localized || statusLabelMap[order.status]
  }

  const getLocalizedTypeLabel = (order: IOrder) => {
    const localized = locale === 'ar' ? order.type_label_ar : order.type_label_en

    return localized || typeLabelMap[order.order_type]
  }

  const statusBreakdownEntries = useMemo(() => {
    if (!statsData?.by_status) return []

    const order: ORDER_STATUS[] = ['pending', 'confirmed', 'preparing', 'ready', 'delivered', 'completed', 'cancelled']

    return order.map(status => ({
      status,
      value: statsData.by_status[status] ?? 0
    }))
  }, [statsData])

  const typeBreakdownEntries = useMemo(() => {
    if (!statsData?.by_type) return []

    const order: ORDER_TYPE[] = ['dine_in', 'takeaway', 'delivery']

    return order.map(type => ({
      type,
      value: statsData.by_type[type] ?? 0
    }))
  }, [statsData])

  // Detect mobile viewport
  useEffect(() => {
    const checkMobile = () => setIsMobile(window.innerWidth < 768)
    checkMobile()
    window.addEventListener('resize', checkMobile)
    return () => window.removeEventListener('resize', checkMobile)
  }, [])

  useEffect(() => {
    setSearchValue(searchParams.get('search') || '')
  }, [searchParamsString])

  useEffect(() => {
    const from = searchParams.get('date_from')
    const to = searchParams.get('date_to')
    setFromDateValue(from ? new Date(from) : null)
    setToDateValue(to ? new Date(to) : null)
    setOrderTypeSelect(orderTypeFilter || '')
    setPaymentStatusSelect((searchParams.get('payment_status') as PAYMENT_STATUS | null) || '')
  }, [orderTypeFilter, searchParamsString])

  useEffect(() => {
    if (statusDialog.order) {
      setStatusForm(statusDialog.order.status)
      setStatusReason('')
    }
  }, [statusDialog])

  useEffect(() => {
    if (paymentDialog.order) {
      setPaymentStatusForm(paymentDialog.order.payment_status)
      setPaymentMethod(paymentDialog.order.payment_method || 'cash')
    }
  }, [paymentDialog])

  const applyFilters = useCallback(
    (updates: Record<string, string | number | undefined>) => {
      const params = new URLSearchParams(searchParamsString)

      Object.entries(updates).forEach(([key, value]) => {
        if (value === undefined || value === null || value === '') {
          params.delete(key)
        } else {
          params.set(key, String(value))
        }
      })

      if (!updates.page) {
        params.set('page', '1')
      }

      const queryString = params.toString()
      router.push(queryString ? `?${queryString}` : '', { scroll: false })
    },
    [router, searchParamsString]
  )

  useEffect(() => {
    const timeout = setTimeout(() => {
      const trimmed = searchValue.trim()
      applyFilters({ search: trimmed || undefined, page: 1 })
    }, 500)

    return () => clearTimeout(timeout)
  }, [searchValue, applyFilters])

  const handleStatusFilter = (value: StatusFilterValue) => {
    applyFilters({ status: value === 'all' ? undefined : value, page: 1 })
  }

  const handlePageSizeChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    applyFilters({ per_page: Number(event.target.value), page: 1 })
  }

  const handleSortChange = (value: OrdersSortField) => {
    applyFilters({ sort_by: value, page: 1 })
  }

  const handleSortDirectionChange = (value: 'asc' | 'desc') => {
    applyFilters({ sort_as: value, page: 1 })
  }

  const handleAdvancedDateChange = (key: 'date_from' | 'date_to', date: Date | null) => {
    const formatted = date ? date.toISOString().split('T')[0] : undefined
    if (key === 'date_from') {
      setFromDateValue(date)
    } else {
      setToDateValue(date)
    }
    applyFilters({ [key]: formatted, page: 1 })
  }

  const handleOrderTypeChange = (value: ORDER_TYPE | '') => {
    setOrderTypeSelect(value)
    applyFilters({ order_type: value || undefined, page: 1 })
  }

  const handlePaymentStatusFilterChange = (value: PAYMENT_STATUS | '') => {
    setPaymentStatusSelect(value)
    applyFilters({ payment_status: value || undefined, page: 1 })
  }

  const handleClearFilters = () => {
    setSearchValue('')
    setOrderLookup('')
    setFromDateValue(null)
    setToDateValue(null)
    setOrderTypeSelect('')
    setPaymentStatusSelect('')
    applyFilters({
      search: undefined,
      status: undefined,
      payment_status: undefined,
      order_type: undefined,
      date_from: undefined,
      date_to: undefined,
      page: 1
    })
  }

  const handlePaginationChange = (updater: any) => {
    const nextState = typeof updater === 'function' ? updater({ pageIndex: page - 1, pageSize: perPage }) : updater
    applyFilters({ page: nextState.pageIndex + 1, per_page: nextState.pageSize })
  }

  // const handleFindOrder = async () => {
  //   if (!orderLookup.trim()) return
  //   try {
  //     const response = await findOrder.mutateAsync(orderLookup.trim())
  //     const orderId = response?.data?.id
  //     if (orderId) {
  //       router.push(`/orders/${orderId}`)
  //       setOrderLookup('')
  //     } else {
  //       toast.info(getSuccessMessage(response as ApiResponse, t('noData')))
  //     }
  //   } catch (error) {
  //     toast.error(getErrorMessage(error, t('noData')))
  //   }
  // }

  // Format currency values
  const formatCurrency = (value?: number | string) => {
    if (value === undefined || value === null) return '$0.00'
    const numeric = typeof value === 'string' ? parseFloat(value) : value
    if (!Number.isNaN(numeric)) {
      return `${numeric.toLocaleString(locale, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}$`
    }
    return '0.00$'
  }

  // Format stat value (non-currency)
  const formatStatValue = (value?: number | string) => {
    if (value === undefined || value === null) return '0'
    const numeric = typeof value === 'string' ? Number(value) : value
    if (!Number.isNaN(numeric)) {
      return numeric.toLocaleString(locale)
    }
    return String(value)
  }

  // Modern stat card component
  const renderModernStatCard = (
    title: string,
    value: number | string | undefined,
    icon: string,
    color: 'primary' | 'success' | 'info' | 'warning' | 'error' | 'secondary',
    isCurrency: boolean = false,
    subtitle?: string
  ) => (
    <Card
      sx={{
        height: '100%',
        background: `linear-gradient(135deg, var(--mui-palette-${color}-main) 0%, var(--mui-palette-${color}-dark) 100%)`,
        color: 'white',
        position: 'relative',
        overflow: 'hidden',
        '&::before': {
          content: '""',
          position: 'absolute',
          top: -50,
          right: -50,
          width: 200,
          height: 200,
          borderRadius: '50%',
          background: 'rgba(255, 255, 255, 0.1)',
          pointerEvents: 'none'
        }
      }}
    >
      <Box sx={{ p: 3, position: 'relative', zIndex: 1 }}>
        <Stack spacing={2}>
          <Stack direction='row' alignItems='center' justifyContent='space-between'>
            <Box
              sx={{
                width: 56,
                height: 56,
                borderRadius: 2,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                bgcolor: 'rgba(255, 255, 255, 0.2)',
                backdropFilter: 'blur(10px)'
              }}
            >
              <i className={`${icon} text-3xl`} style={{ color: 'white' }} />
            </Box>
            {statsLoading && !statsData ? <CircularProgress size={20} sx={{ color: 'white' }} /> : null}
          </Stack>
          <Box>
            <Typography variant='h4' fontWeight={700} sx={{ color: 'white', mb: 0.5 }}>
              {statsLoading && !statsData ? (
                <Box sx={{ width: 100, height: 32, bgcolor: 'rgba(255, 255, 255, 0.2)', borderRadius: 1 }} />
              ) : isCurrency ? (
                formatCurrency(value)
              ) : (
                formatStatValue(value)
              )}
            </Typography>
            <Typography variant='body1' sx={{ color: 'rgba(255, 255, 255, 0.9)', fontWeight: 500 }}>
              {title}
            </Typography>
            {subtitle && (
              <Typography variant='body2' sx={{ color: 'rgba(255, 255, 255, 0.7)' }}>
                {subtitle}
              </Typography>
            )}
          </Box>
        </Stack>
      </Box>
    </Card>
  )

  const columns = useMemo<ColumnDef<IOrder, any>[]>(() => {
    const baseColumns: ColumnDef<IOrder, any>[] = [
      columnHelper.accessor('order_number', {
        header: t('orderNumber'),
        cell: ({ row }) => (
          <Stack spacing={1}>
            <Link href={`/orders/${row.original.id}`} className='font-semibold text-primary'>
              {row.original.order_number}
            </Link>
          </Stack>
        )
      }),

      columnHelper.accessor('customer_name', {
        header: t('customer'),
        cell: ({ row }) => (
          <Stack spacing={0.5}>
            <Typography fontWeight={600}>{row.original.customer_name}</Typography>
            <Typography variant='body2' color='text.secondary' dir='ltr' sx={{ textAlign: 'left' }}>
              {row.original.customer_phone}
            </Typography>
            {row.original.table && (
              <Typography variant='body2' color='text.secondary'>
                {t('table', { table: row.original.table.table_number })}
              </Typography>
            )}
          </Stack>
        )
      }),
      columnHelper.accessor('items', {
        header: t('total'),
        cell: ({ row }) => (
          <Stack spacing={0.5}>
            <Typography fontWeight={600}>{formatCurrency(row.original.total_amount)}</Typography>
            <Typography variant='caption' color='text.secondary'>
              {t('itemsCount', { count: row.original.items?.length || 0 })}
            </Typography>
          </Stack>
        )
      }),
      columnHelper.accessor('status', {
        header: t('status'),
        cell: ({ row }) => (
          <Chip
            size='small'
            icon={<i className={`${statusChipMeta[row.original.status].icon} text-base`} />}
            label={getLocalizedStatusLabel(row.original)}
            color={statusChipMeta[row.original.status].color}
            variant='outlined'
          />
        )
      }),
      columnHelper.accessor('order_type', {
        header: t('type'),
        cell: ({ row }) => (
          <Chip
            size='small'
            variant='outlined'
            color={typeChipMeta[row.original.order_type].color}
            icon={<i className={`${typeChipMeta[row.original.order_type].icon} text-base`} />}
            label={getLocalizedTypeLabel(row.original)}
          />
        )
      }),
      columnHelper.accessor('payment_status', {
        header: t('paymentStatus'),
        cell: ({ row }) => (
          <Chip
            size='small'
            color={paymentChipMeta[row.original.payment_status].color}
            icon={<i className={`${paymentChipMeta[row.original.payment_status].icon} text-base`} />}
            label={
              (locale === 'ar' ? row.original.payment_label_ar : row.original.payment_label_en) ||
              row.original.payment_label_en ||
              row.original.payment_label_ar ||
              t(`paymentLabels.${row.original.payment_status}` as any)
            }
            variant='outlined'
          />
        )
      })
    ]

    baseColumns.push(
      columnHelper.accessor('created_at', {
        header: t('createdAt'),
        cell: ({ row }) => (
          <Typography variant='body2'>{new Date(row.original.created_at).toLocaleString(locale)}</Typography>
        )
      }),
      {
        id: 'actions',
        header: t('ACTIONS'),
        cell: ({ row }) => (
          <Stack direction='row' spacing={1}>
            <Button
              size='small'
              variant='outlined'
              startIcon={<i className='tabler-eye' />}
              onClick={() => router.push(`/orders/${row.original.id}`)}
            >
              {t('view')}
            </Button>
            <Tooltip title={t('status')}>
              <IconButton size='small' onClick={() => setStatusDialog({ open: true, order: row.original })}>
                <i className='tabler-arrows-shuffle' />
              </IconButton>
            </Tooltip>
            <Tooltip title={t('paymentStatus')}>
              <IconButton
                size='small'
                color='secondary'
                onClick={() => setPaymentDialog({ open: true, order: row.original })}
              >
                <i className='tabler-credit-card' />
              </IconButton>
            </Tooltip>
          </Stack>
        )
      }
    )

    return baseColumns
  }, [locale, router, t, isMobile, statusLabelMap, typeLabelMap])

  const table = useReactTable({
    data: rows,
    columns,
    manualPagination: true,
    pageCount: Math.max(1, Math.ceil(total / perPage)),
    state: {
      pagination: {
        pageIndex: page - 1,
        pageSize: perPage
      }
    },
    onPaginationChange: handlePaginationChange,
    getCoreRowModel: getCoreRowModel(),
    filterFns: {
      fuzzy: noopFilter
    }
  })

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

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

  return (
    <>
      {/* Top Toolbar */}
      {/* <Card className='p-4 mb-4'>
        <Stack direction='row' spacing={2} flexWrap='wrap' alignItems='end'>
          <CustomTextField
            placeholder={t('searchPlaceholder')}
            value={searchValue}
            onChange={e => setSearchValue(e.target.value)}
            className='min-w-[220px] flex-1'
            slotProps={{ input: { startAdornment: <i className='tabler-search mr-2' /> } }}
          />
          <div className='flex items-center gap-2 flex-1 min-w-[220px]'>
            <CustomTextField
              label={t('lookupPlaceholder')}
              size='small'
              value={orderLookup}
              onChange={e => setOrderLookup(e.target.value)}
              fullWidth
            />
            <Button
              variant='contained'
              onClick={handleFindOrder}
              disabled={findOrder.isPending}
              startIcon={
                findOrder.isPending ? <CircularProgress size={16} color='inherit' /> : <i className='tabler-search' />
              }
            >
              {t('findOrder')}
            </Button>
          </div>
          {activeFiltersCount > 0 && (
            <Button
              size='small'
              variant='text'
              color='error'
              onClick={handleClearFilters}
              startIcon={<i className='tabler-refresh' />}
            >
              {t('clearFilters')}
            </Button>
          )}
        </Stack>
      </Card> */}

      {/* Modern Stats Cards */}
      <Grid container spacing={3} mb={4}>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          {renderModernStatCard(
            t('stats.todayOrders'),
            todayStats?.total_orders,
            'tabler-shopping-cart',
            'primary',
            false,
            t('summary.today')
          )}
        </Grid>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          {renderModernStatCard(
            t('stats.todayRevenue'),
            todayStats?.revenue,
            'tabler-cash',
            'success',
            true,
            t('summary.today')
          )}
        </Grid>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          {renderModernStatCard(
            t('stats.monthOrders'),
            monthStats?.total_orders,
            'tabler-calendar-stats',
            'info',
            false,
            t('summary.month')
          )}
        </Grid>
        <Grid size={{ xs: 12, sm: 6, md: 3 }}>
          {renderModernStatCard(
            t('stats.monthRevenue'),
            monthStats?.revenue,
            'tabler-chart-line',
            'warning',
            true,
            t('summary.month')
          )}
        </Grid>
      </Grid>

      {/* Breakdown Cards */}
      {(statsLoading || statsData) && (
        <Grid container spacing={3} mb={4} alignItems='stretch'>
          <Grid size={{ xs: 12, md: 6 }} sx={{ height: '100%', display: 'flex' }}>
            <Card sx={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 160 }}>
              <Box sx={{ p: 3, flex: 1 }}>
                <Stack direction='row' alignItems='center' spacing={2} mb={2}>
                  <Box
                    sx={{
                      width: 40,
                      height: 40,
                      borderRadius: 2,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      bgcolor: 'primary.lighter'
                    }}
                  >
                    <i className='tabler-chart-pie text-xl' style={{ color: 'var(--mui-palette-primary-main)' }} />
                  </Box>
                  <Typography variant='h6' fontWeight={600}>
                    {t('statusBreakdown')}
                  </Typography>
                </Stack>
                {statsLoading && !statsData ? (
                  <div className='flex items-center justify-center py-4'>
                    <CircularProgress size={20} />
                  </div>
                ) : statusBreakdownEntries.length > 0 ? (
                  <Stack direction='row' flexWrap='wrap' gap={1.5}>
                    {statusBreakdownEntries.map(item => (
                      <Chip
                        key={item.status}
                        size='medium'
                        color={statusChipMeta[item.status].color}
                        icon={<i className={`${statusChipMeta[item.status].icon} text-base`} />}
                        label={`${statusLabelMap[item.status]} • ${item.value}`}
                        sx={{ fontWeight: 500 }}
                      />
                    ))}
                  </Stack>
                ) : (
                  <Typography color='text.secondary'>{t('noData')}</Typography>
                )}
              </Box>
            </Card>
          </Grid>
          <Grid size={{ xs: 12, md: 6 }} sx={{ height: '100%', display: 'flex' }}>
            <Card sx={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 160 }}>
              <Box sx={{ p: 3, flex: 1 }}>
                <Stack direction='row' alignItems='center' spacing={2} mb={2}>
                  <Box
                    sx={{
                      width: 40,
                      height: 40,
                      borderRadius: 2,
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      bgcolor: 'secondary.lighter'
                    }}
                  >
                    <i className='tabler-category text-xl' style={{ color: 'var(--mui-palette-secondary-main)' }} />
                  </Box>
                  <Typography variant='h6' fontWeight={600}>
                    {t('typeBreakdown')}
                  </Typography>
                </Stack>
                {statsLoading && !statsData ? (
                  <div className='flex items-center justify-center py-4'>
                    <CircularProgress size={20} />
                  </div>
                ) : typeBreakdownEntries.length > 0 ? (
                  <Stack direction='row' flexWrap='wrap' gap={1.5}>
                    {typeBreakdownEntries.map(item => (
                      <Chip
                        key={item.type}
                        size='medium'
                        color={typeChipMeta[item.type].color}
                        icon={<i className={`${typeChipMeta[item.type].icon} text-base`} />}
                        label={`${typeLabelMap[item.type]} • ${item.value}`}
                        sx={{ fontWeight: 500 }}
                      />
                    ))}
                  </Stack>
                ) : (
                  <Typography color='text.secondary'>{t('noData')}</Typography>
                )}
              </Box>
            </Card>
          </Grid>
        </Grid>
      )}

      <Card className='p-4 mb-4'>
        <Stack direction='row' spacing={2} flexWrap='wrap' alignItems='end'>
          <CustomTextField
            placeholder={t('searchPlaceholder')}
            value={searchValue}
            onChange={e => setSearchValue(e.target.value)}
            className='min-w-[220px] flex-1'
            slotProps={{ input: { startAdornment: <i className='tabler-search mr-2' /> } }}
          />
        </Stack>
      </Card>

      {/* Dropdown Filters */}
      <Card className='p-4 mb-4'>
        <Grid container spacing={3}>
          {/* Status Filter Dropdown */}
          <Grid size={{ xs: 12, sm: 6, md: 3 }}>
            <CustomTextField
              select
              fullWidth
              label={t('statusFilter')}
              value={statusFilter}
              onChange={e => handleStatusFilter(e.target.value as StatusFilterValue)}
              slotProps={{
                select: {
                  renderValue: value => {
                    const val = value as StatusFilterValue
                    if (val === 'all') {
                      return (
                        <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
                          <i className='tabler-adjustments' />
                          <span>{t('statusFilters.all')}</span>
                        </Box>
                      )
                    }
                    const meta = statusChipMeta[val]
                    return (
                      <Chip
                        size='small'
                        icon={<i className={`${meta.icon} text-base`} />}
                        label={statusLabelMap[val]}
                        color={meta.color}
                      />
                    )
                  }
                }
              }}
            >
              <MenuItem value='all'>
                <Stack direction='row' spacing={1} alignItems='center'>
                  <i className='tabler-adjustments' />
                  <span>{t('statusFilters.all')}</span>
                </Stack>
              </MenuItem>
              {(Object.keys(statusChipMeta) as ORDER_STATUS[]).map(status => (
                <MenuItem key={status} value={status}>
                  <Stack direction='row' spacing={1} alignItems='center'>
                    <i
                      className={statusChipMeta[status].icon}
                      style={{ color: `var(--mui-palette-${statusChipMeta[status].color}-main)` }}
                    />
                    <span>{statusLabelMap[status]}</span>
                  </Stack>
                </MenuItem>
              ))}
            </CustomTextField>
          </Grid>

          {/* Order Type Filter Dropdown */}
          <Grid size={{ xs: 12, sm: 6, md: 3 }}>
            <CustomTextField
              select
              fullWidth
              label={t('orderTypeFilter')}
              value={orderTypeSelect || 'all'}
              onChange={e => handleOrderTypeChange(e.target.value === 'all' ? '' : (e.target.value as ORDER_TYPE))}
              slotProps={{
                select: {
                  renderValue: value => {
                    if (value === 'all' || !value) {
                      return (
                        <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
                          <i className='tabler-category' />
                          <span>{t('allTypes')}</span>
                        </Box>
                      )
                    }
                    const meta = typeChipMeta[value as ORDER_TYPE]
                    return (
                      <Chip
                        size='small'
                        icon={<i className={`${meta.icon} text-base`} />}
                        label={typeLabelMap[value as ORDER_TYPE]}
                        color={meta.color}
                      />
                    )
                  }
                }
              }}
            >
              <MenuItem value='all'>
                <Stack direction='row' spacing={1} alignItems='center'>
                  <i className='tabler-category' />
                  <span>{t('allTypes')}</span>
                </Stack>
              </MenuItem>
              {(Object.keys(typeChipMeta) as ORDER_TYPE[]).map(type => (
                <MenuItem key={type} value={type}>
                  <Stack direction='row' spacing={1} alignItems='center'>
                    <i
                      className={typeChipMeta[type].icon}
                      style={{ color: `var(--mui-palette-${typeChipMeta[type].color}-main)` }}
                    />
                    <span>{typeLabelMap[type]}</span>
                  </Stack>
                </MenuItem>
              ))}
            </CustomTextField>
          </Grid>

          {/* Payment Status Filter Dropdown */}
          <Grid size={{ xs: 12, sm: 6, md: 3 }}>
            <CustomTextField
              select
              fullWidth
              label={t('paymentStatusFilter')}
              value={paymentStatusSelect || 'all'}
              onChange={e =>
                handlePaymentStatusFilterChange(e.target.value === 'all' ? '' : (e.target.value as PAYMENT_STATUS))
              }
              slotProps={{
                select: {
                  renderValue: value => {
                    if (value === 'all' || !value) {
                      return (
                        <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
                          <i className='tabler-credit-card' />
                          <span>{t('allPayments')}</span>
                        </Box>
                      )
                    }
                    const meta = paymentChipMeta[value as PAYMENT_STATUS]
                    return (
                      <Chip
                        size='small'
                        icon={<i className={`${meta.icon} text-base`} />}
                        label={t(`paymentLabels.${value}` as any)}
                        color={meta.color}
                      />
                    )
                  }
                }
              }}
            >
              <MenuItem value='all'>
                <Stack direction='row' spacing={1} alignItems='center'>
                  <i className='tabler-credit-card' />
                  <span>{t('allPayments')}</span>
                </Stack>
              </MenuItem>
              {(Object.keys(paymentChipMeta) as PAYMENT_STATUS[]).map(status => (
                <MenuItem key={status} value={status}>
                  <Stack direction='row' spacing={1} alignItems='center'>
                    <i
                      className={paymentChipMeta[status].icon}
                      style={{ color: `var(--mui-palette-${paymentChipMeta[status].color}-main)` }}
                    />
                    <span>{t(`paymentLabels.${status}` as any)}</span>
                  </Stack>
                </MenuItem>
              ))}
            </CustomTextField>
          </Grid>

          {/* Date & Sort Filters */}
          <Grid size={{ xs: 12, sm: 6, md: 3 }}>
            <CustomTextField
              select
              fullWidth
              label={t('sortBy')}
              value={sortField}
              onChange={e => handleSortChange(e.target.value as OrdersSortField)}
              slotProps={{ input: { startAdornment: <i className='tabler-sort-ascending mr-2' /> } }}
            >
              <MenuItem value='created_at'>{t('sort.created')}</MenuItem>
              <MenuItem value='total_amount'>{t('sort.total')}</MenuItem>
              <MenuItem value='order_number'>{t('sort.number')}</MenuItem>
            </CustomTextField>
          </Grid>

          <Grid size={{ xs: 12, sm: 6, md: 3 }}>
            <CustomTextField
              select
              fullWidth
              label={t('sortDirection')}
              value={sortDirection}
              onChange={e => handleSortDirectionChange(e.target.value as 'asc' | 'desc')}
              slotProps={{ input: { startAdornment: <i className='tabler-arrows-sort mr-2' /> } }}
            >
              <MenuItem value='desc'>{t('sort.desc')}</MenuItem>
              <MenuItem value='asc'>{t('sort.asc')}</MenuItem>
            </CustomTextField>
          </Grid>

          <Grid size={{ xs: 12, sm: 6, md: 3 }}>
            <AppReactDatepicker
              selected={fromDateValue}
              dateFormat='yyyy-MM-dd'
              onChange={date => handleAdvancedDateChange('date_from', date)}
              customInput={
                <CustomTextField
                  label={t('fromDate')}
                  value={fromDateValue ? fromDateValue.toLocaleDateString(locale) : ''}
                  fullWidth
                  slotProps={{ input: { startAdornment: <i className='tabler-calendar mr-2' /> } }}
                />
              }
            />
          </Grid>

          <Grid size={{ xs: 12, sm: 6, md: 3 }}>
            <AppReactDatepicker
              selected={toDateValue}
              minDate={fromDateValue || undefined}
              dateFormat='yyyy-MM-dd'
              onChange={date => handleAdvancedDateChange('date_to', date)}
              customInput={
                <CustomTextField
                  label={t('toDate')}
                  value={toDateValue ? toDateValue.toLocaleDateString(locale) : ''}
                  fullWidth
                  slotProps={{ input: { startAdornment: <i className='tabler-calendar mr-2' /> } }}
                />
              }
            />
          </Grid>

          <Grid size={{ xs: 12, sm: 6, md: 3 }} alignSelf={'flex-end'}>
            <Button
              size='small'
              color='error'
              variant='outlined'
              onClick={handleClearFilters}
              startIcon={<i className='tabler-refresh' />}
            >
              {t('clearFilters')}
            </Button>
          </Grid>
        </Grid>
      </Card>

      {/* Orders Table */}
      <Card>
        <div className='overflow-x-auto'>
          <table className={tableStyles.table}>
            <thead>
              {table.getHeaderGroups().map(headerGroup => (
                <tr key={headerGroup.id}>
                  {headerGroup.headers.map(header => (
                    <th key={header.id}>{flexRender(header.column.columnDef.header, header.getContext())}</th>
                  ))}
                </tr>
              ))}
            </thead>
            <tbody>
              {isLoading ? (
                Array.from({ length: perPage }).map((_, i) => (
                  <tr key={`skeleton-${i}`}>
                    {table.getVisibleFlatColumns().map(column => (
                      <td key={`${column.id}-${i}`}>
                        <div className='h-4 w-full bg-gray-200 animate-pulse rounded' />
                      </td>
                    ))}
                  </tr>
                ))
              ) : rows.length === 0 ? (
                <tr>
                  <td colSpan={table.getVisibleFlatColumns().length}>
                    <Alert severity='info' className='m-4'>
                      {t('noData')}
                    </Alert>
                  </td>
                </tr>
              ) : (
                table.getRowModel().rows.map(row => (
                  <tr key={row.id}>
                    {row.getVisibleCells().map(cell => (
                      <td key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</td>
                    ))}
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
        <Divider />
        <div className='flex flex-wrap items-center justify-between gap-4 px-6 py-4'>
          <CustomTextField select value={perPage} onChange={handlePageSizeChange} className='w-28'>
            <MenuItem value={5}>5</MenuItem>
            <MenuItem value={10}>10</MenuItem>
            <MenuItem value={15}>15</MenuItem>
            <MenuItem value={25}>25</MenuItem>
            <MenuItem value={50}>50</MenuItem>
          </CustomTextField>
          <CustomTablePaginationComponent table={table} totalItems={total} />
        </div>
      </Card>

      {/* Status Update Dialog */}
      <Dialog
        open={statusDialog.open}
        onClose={() => setStatusDialog({ open: false, order: null })}
        maxWidth='xs'
        fullWidth
      >
        <DialogTitle>{t('statusDialog.title', { order: statusDialog.order?.order_number || '' })}</DialogTitle>
        <DialogContent className='flex flex-col gap-4 mt-2'>
          <CustomTextField
            select
            label={t('status')}
            value={statusForm}
            onChange={e => setStatusForm(e.target.value as ORDER_STATUS)}
            fullWidth
          >
            {(Object.keys(statusChipMeta) as ORDER_STATUS[]).map(status => (
              <MenuItem key={status} value={status}>
                <Stack direction='row' spacing={1} alignItems='center'>
                  <i className={statusChipMeta[status].icon} />
                  <span>{statusLabelMap[status]}</span>
                </Stack>
              </MenuItem>
            ))}
          </CustomTextField>
          {statusForm === 'cancelled' && (
            <CustomTextField
              multiline
              rows={3}
              label={t('statusDialog.reason')}
              value={statusReason}
              onChange={e => setStatusReason(e.target.value)}
              required
            />
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setStatusDialog({ open: false, order: null })}>{t('cancel')}</Button>
          <Button
            onClick={handleStatusSubmit}
            variant='contained'
            disabled={updateStatus.isPending || (statusForm === 'cancelled' && !statusReason.trim())}
            startIcon={
              updateStatus.isPending ? (
                <CircularProgress size={16} color='inherit' />
              ) : (
                <i className='tabler-device-floppy' />
              )
            }
          >
            {t('save')}
          </Button>
        </DialogActions>
      </Dialog>

      {/* Payment Update Dialog */}
      <Dialog
        open={paymentDialog.open}
        onClose={() => setPaymentDialog({ open: false, order: null })}
        maxWidth='xs'
        fullWidth
      >
        <DialogTitle>{t('paymentDialog.title', { order: paymentDialog.order?.order_number || '' })}</DialogTitle>
        <DialogContent className='flex flex-col gap-4 mt-2'>
          <CustomTextField
            select
            label={t('paymentStatus')}
            value={paymentStatusForm}
            onChange={e => setPaymentStatusForm(e.target.value as PAYMENT_STATUS)}
            fullWidth
          >
            {(Object.keys(paymentChipMeta) as PAYMENT_STATUS[]).map(status => (
              <MenuItem key={status} value={status}>
                <Stack direction='row' spacing={1} alignItems='center'>
                  <i className={paymentChipMeta[status].icon} />
                  <span>{t(`paymentLabels.${status}` as any)}</span>
                </Stack>
              </MenuItem>
            ))}
          </CustomTextField>
          <CustomTextField
            label={t('paymentDialog.method')}
            value={paymentMethod}
            onChange={e => setPaymentMethod(e.target.value)}
            fullWidth
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setPaymentDialog({ open: false, order: null })}>{t('cancel')}</Button>
          <Button
            onClick={handlePaymentSubmit}
            variant='contained'
            disabled={updatePayment.isPending}
            startIcon={
              updatePayment.isPending ? (
                <CircularProgress size={16} color='inherit' />
              ) : (
                <i className='tabler-device-floppy' />
              )
            }
          >
            {t('save')}
          </Button>
        </DialogActions>
      </Dialog>
    </>
  )
}

export default OrdersView
