'use client';

import { useState, useEffect, useCallback, useRef } from 'react';
import {
  Search, ChevronLeft, ChevronRight, X, Loader2,
  ShoppingBag, DollarSign, Clock, CheckCircle2, XCircle,
  Zap, Package, ChevronDown
} from 'lucide-react';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

interface OrderItem {
  name: string;
  quantity: number;
  price?: number;
  modifiers?: string[];
  special_instructions?: string;
}

interface Order {
  id: string;
  order_number: number;
  restaurant_id: string;
  restaurant_name: string;
  branch_id: string | null;
  branch_name: string | null;
  customer_id: string | null;
  customer_name: string | null;
  customer_phone: string | null;
  customer_email: string | null;
  customer_full_name: string | null;
  customer_full_email: string | null;
  items: OrderItem[];
  status: string;
  channel: string;
  source: string | null;
  delivery_type: string | null;
  subtotal: number;
  tax: number;
  total: number;
  discount_amount?: number | null;
  coupon_code?: string | null;
  gift_card_applied?: number | null;
  gift_card_remaining_balance?: number | null;
  table_number: string | null;
  delivery_address: string | null;
  special_instructions: string | null;
  modification_note: string | null;
  is_modified: boolean;
  ai_confidence: number | null;
  agent_id: string | null;
  conversation_id: string | null;
  created_at: string;
  updated_at: string;
}

interface Stats {
  total: number;
  pending: number;
  active: number;
  completed: number;
  cancelled: number;
  revenue: number;
}

interface AdminRestaurant { id: string; name: string; }

const ALL_ORDER_STATUSES = ['pending','confirmed','kitchen','ready','delivered','completed','cancelled','failed','escalated','processing','rider'];

const STATUS_COLORS: Record<string, string> = {
  pending: 'badge-warning',
  confirmed: 'badge-primary',
  kitchen: 'badge-primary',
  ready: 'badge-info',
  delivered: 'badge-success',
  completed: 'badge-success',
  cancelled: 'badge-danger',
  failed: 'badge-danger',
  escalated: 'badge-danger',
  processing: 'badge-primary',
  rider: 'badge-info',
};

const CHANNEL_COLORS: Record<string, string> = {
  chat: 'badge-primary',
  voice: 'badge-info',
  whatsapp: 'badge-success',
  email: 'badge-neutral',
  sms: 'badge-neutral',
  manual: 'badge-neutral',
  storefront: 'badge-warning',
};

const SOURCE_LABELS: Record<string, string> = {
  storefront: 'Storefront',
  qr: 'QR / Dine-in',
  pos: 'POS',
  api: 'API',
  agent: 'AI Agent',
};

function fmt(amount: number) {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);
}

function fmtDate(iso: string) {
  return new Date(iso).toLocaleString('en-US', {
    month: 'short', day: 'numeric', year: 'numeric',
    hour: '2-digit', minute: '2-digit',
  });
}

function StatCard({ icon, label, value }: { icon: React.ReactNode; label: string; value: string | number }) {
  return (
    <div className="card p-4 flex items-center gap-3">
      <div className="w-9 h-9 rounded-lg flex items-center justify-center shrink-0" style={{ backgroundColor: 'hsl(var(--primary-light))' }}>
        {icon}
      </div>
      <div className="min-w-0">
        <p className="text-xs font-medium truncate" style={{ color: 'hsl(var(--muted-foreground))' }}>{label}</p>
        <p className="text-lg font-bold leading-tight" style={{ color: 'hsl(var(--foreground))' }}>{value}</p>
      </div>
    </div>
  );
}

function StatusMultiSelect({
  options,
  selected,
  onChange,
  placeholder,
}: {
  options: string[];
  selected: string[];
  onChange: (val: string[]) => void;
  placeholder: string;
}) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    }
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, []);

  const toggle = (opt: string) => {
    onChange(selected.includes(opt) ? selected.filter(s => s !== opt) : [...selected, opt]);
  };

  const label = selected.length === 0
    ? placeholder
    : selected.length === 1
      ? selected[0]
      : `${selected.length} statuses`;

  return (
    <div ref={ref} className="relative">
      <button
        type="button"
        className="input-base text-sm flex items-center gap-2 min-w-36"
        onClick={() => setOpen(o => !o)}
      >
        <span className="flex-1 text-left truncate" style={{ color: selected.length === 0 ? 'hsl(var(--muted-foreground))' : 'hsl(var(--foreground))' }}>{label}</span>
        <ChevronDown size={13} style={{ color: 'hsl(var(--muted-foreground))' }} />
      </button>
      {open && (
        <div className="absolute top-full left-0 mt-1 z-30 rounded-xl shadow-lg overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))', minWidth: '160px' }}>
          {options.map(opt => (
            <label key={opt} className="flex items-center gap-2.5 px-3 py-2 cursor-pointer hover:bg-black/5 text-sm capitalize" style={{ color: 'hsl(var(--foreground))' }}>
              <input
                type="checkbox"
                checked={selected.includes(opt)}
                onChange={() => toggle(opt)}
                className="accent-primary w-3.5 h-3.5"
              />
              {opt}
            </label>
          ))}
          {selected.length > 0 && (
            <button
              type="button"
              onClick={() => onChange([])}
              className="w-full text-left px-3 py-2 text-xs hover:bg-black/5"
              style={{ color: 'hsl(var(--muted-foreground))', borderTop: '1px solid hsl(var(--border))' }}
            >
              Clear selection
            </button>
          )}
        </div>
      )}
    </div>
  );
}

function OrderDrawer({ orderId, listOrder, onClose }: { orderId: string; listOrder: Order; onClose: () => void }) {
  const { t } = useLanguage();
  const [order, setOrder] = useState<Order>(listOrder);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`/api/admin/orders/${orderId}`, { credentials: 'include' })
      .then(r => r.json())
      .then(d => { if (d.order) setOrder(d.order as Order); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [orderId]);

  const items: OrderItem[] = Array.isArray(order.items) ? order.items : [];
  const displayName = order.customer_full_name ?? order.customer_name;
  const displayEmail = order.customer_full_email ?? order.customer_email;

  return (
    <div className="fixed inset-0 z-50 flex justify-end" style={{ backgroundColor: 'rgba(0,0,0,0.4)' }} onClick={onClose}>
      <div
        className="h-full overflow-y-auto shadow-2xl"
        style={{ width: '420px', backgroundColor: 'hsl(var(--surface))', borderLeft: '1px solid hsl(var(--border))' }}
        onClick={e => e.stopPropagation()}
      >
        <div className="sticky top-0 z-10 flex items-center justify-between px-5 py-4" style={{ borderBottom: '1px solid hsl(var(--border))', backgroundColor: 'hsl(var(--surface))' }}>
          <div>
            <h3 className="font-bold text-base" style={{ color: 'hsl(var(--foreground))' }}>
              {t('admin.orders.orderHash', 'Order')} #{order.order_number}
            </h3>
            <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{fmtDate(order.created_at)}</p>
          </div>
          <div className="flex items-center gap-2">
            {loading && <Loader2 size={15} className="animate-spin" style={{ color: 'hsl(var(--muted-foreground))' }} />}
            <button onClick={onClose} className="btn-ghost p-1.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
              <X size={18} />
            </button>
          </div>
        </div>

        <div className="p-5 space-y-5">
          <div className="flex flex-wrap gap-2">
            <span className={`badge ${STATUS_COLORS[order.status] ?? 'badge-neutral'} capitalize`}>{order.status}</span>
            <span className={`badge ${CHANNEL_COLORS[order.channel] ?? 'badge-neutral'} capitalize`}>{order.channel}</span>
            {order.source && (SOURCE_LABELS[order.source] || order.source !== order.channel) && (
              <span className={`badge ${order.source === 'storefront' ? 'badge-warning' : 'badge-neutral'} ml-1`}>{SOURCE_LABELS[order.source] ?? order.source}</span>
            )}
            {order.delivery_type && <span className="badge badge-neutral capitalize">{order.delivery_type.replace('-', ' ')}</span>}
            {order.is_modified && <span className="badge badge-warning">Modified</span>}
          </div>

          <div className="rounded-xl p-4 space-y-1" style={{ border: '1px solid hsl(var(--border))' }}>
            <p className="text-xs font-semibold mb-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.orders.restaurant', 'Restaurant')}</p>
            <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{order.restaurant_name ?? '—'}</p>
            {order.branch_name && <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{order.branch_name}</p>}
          </div>

          <div className="rounded-xl p-4 space-y-1" style={{ border: '1px solid hsl(var(--border))' }}>
            <p className="text-xs font-semibold mb-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.orders.customer', 'Customer')}</p>
            <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{displayName ?? '—'}</p>
            {order.customer_phone && <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{order.customer_phone}</p>}
            {displayEmail && <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{displayEmail}</p>}
          </div>

          {(order.table_number || order.delivery_address) && (
            <div className="rounded-xl p-4" style={{ border: '1px solid hsl(var(--border))' }}>
              <p className="text-xs font-semibold mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>
                {order.delivery_type === 'delivery' ? t('admin.orders.deliveryAddress', 'Delivery Address') : t('admin.orders.tableNumber', 'Table Number')}
              </p>
              <p className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>
                {order.delivery_address ?? order.table_number ?? '—'}
              </p>
            </div>
          )}

          <div>
            <p className="text-xs font-semibold mb-3" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.orders.items', 'Items')}</p>
            <div className="space-y-2">
              {items.length === 0 ? (
                <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>No items</p>
              ) : items.map((item, i) => (
                <div key={i} className="flex gap-3 items-start rounded-lg p-3" style={{ border: '1px solid hsl(var(--border))' }}>
                  <span className="w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold shrink-0 mt-0.5" style={{ backgroundColor: 'hsl(var(--primary))', color: 'white' }}>
                    {item.quantity}
                  </span>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium" style={{ color: 'hsl(var(--foreground))' }}>{item.name}</p>
                    {item.modifiers && item.modifiers.length > 0 && (
                      <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{item.modifiers.join(', ')}</p>
                    )}
                    {item.special_instructions && (
                      <p className="text-xs mt-0.5 italic" style={{ color: 'hsl(var(--muted-foreground))' }}>{item.special_instructions}</p>
                    )}
                  </div>
                  {item.price != null && (
                    <span className="text-sm font-semibold shrink-0" style={{ color: 'hsl(var(--foreground))' }}>{fmt(item.price * item.quantity)}</span>
                  )}
                </div>
              ))}
            </div>
          </div>

          <div className="rounded-xl p-4 space-y-2" style={{ border: '1px solid hsl(var(--border))' }}>
            <div className="flex justify-between text-sm">
              <span style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.orders.subtotal', 'Subtotal')}</span>
              <span style={{ color: 'hsl(var(--foreground))' }}>{fmt(order.subtotal)}</span>
            </div>
            {Number(order.discount_amount ?? 0) > 0 && (
              <div className="flex justify-between text-sm">
                <span style={{ color: 'hsl(142 71% 35%)' }}>
                  {t('admin.orders.discount', 'Discount')}{order.coupon_code ? ` (${order.coupon_code})` : ''}
                </span>
                <span style={{ color: 'hsl(142 71% 35%)' }}>−{fmt(Number(order.discount_amount ?? 0))}</span>
              </div>
            )}
            <div className="flex justify-between text-sm">
              <span style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.orders.tax', 'Tax')}</span>
              <span style={{ color: 'hsl(var(--foreground))' }}>{fmt(order.tax)}</span>
            </div>
            {Number(order.gift_card_applied ?? 0) > 0 && (
              <div className="flex justify-between text-sm">
                <span style={{ color: 'hsl(217 91% 50%)' }}>{t('admin.orders.giftCard', 'Gift card')}</span>
                <span style={{ color: 'hsl(217 91% 50%)' }}>−{fmt(Number(order.gift_card_applied ?? 0))}</span>
              </div>
            )}
            <div className="flex justify-between font-bold text-sm pt-2" style={{ borderTop: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}>
              <span>{Number(order.gift_card_applied ?? 0) > 0 ? t('admin.orders.totalPaid', 'Total paid') : t('admin.orders.total', 'Total')}</span>
              <span>{fmt(order.total)}</span>
            </div>
            {Number(order.gift_card_applied ?? 0) > 0 && order.gift_card_remaining_balance != null && (
              <div className="flex justify-between text-xs">
                <span style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.orders.giftCardBalance', 'Gift card balance')}</span>
                <span style={{ color: 'hsl(var(--muted-foreground))' }}>{fmt(Number(order.gift_card_remaining_balance))}</span>
              </div>
            )}
          </div>

          {order.special_instructions && (
            <div className="rounded-xl p-4" style={{ border: '1px solid hsl(var(--border))' }}>
              <p className="text-xs font-semibold mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.orders.specialInstructions', 'Special Instructions')}</p>
              <p className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>{order.special_instructions}</p>
            </div>
          )}

          {order.modification_note && (
            <div className="rounded-xl p-4" style={{ border: '1px solid hsl(var(--border))' }}>
              <p className="text-xs font-semibold mb-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.orders.modificationNote', 'Modification Note')}</p>
              <p className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>{order.modification_note}</p>
            </div>
          )}

          <div className="rounded-xl p-4 space-y-1.5" style={{ border: '1px solid hsl(var(--border))' }}>
            <p className="text-xs font-semibold mb-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.orders.metadata', 'Metadata')}</p>
            {order.agent_id && <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>Agent: <span style={{ color: 'hsl(var(--foreground))' }} className="font-mono">{order.agent_id}</span></p>}
            {order.conversation_id && <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>Conversation: <span style={{ color: 'hsl(var(--foreground))' }} className="font-mono">{order.conversation_id.slice(0, 16)}…</span></p>}
            {order.ai_confidence != null && <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>AI Confidence: <span style={{ color: 'hsl(var(--foreground))' }}>{Math.round(order.ai_confidence * 100)}%</span></p>}
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>Updated: <span style={{ color: 'hsl(var(--foreground))' }}>{fmtDate(order.updated_at)}</span></p>
            <p className="text-xs font-mono break-all" style={{ color: 'hsl(var(--muted-foreground))' }}>ID: {order.id}</p>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function AdminOrdersPage() {
  const { t } = useLanguage();
  usePageHeader(
    t('admin.orders.pageTitle', 'Orders'),
    t('admin.orders.pageDesc', 'All orders across every restaurant and branch')
  );

  const [orders, setOrders] = useState<Order[]>([]);
  const [stats, setStats] = useState<Stats>({ total: 0, pending: 0, active: 0, completed: 0, cancelled: 0, revenue: 0 });
  const [restaurants, setRestaurants] = useState<AdminRestaurant[]>([]);
  const [branches, setBranches] = useState<{ id: string; name: string }[]>([]);
  const [total, setTotal] = useState(0);
  const [pages, setPages] = useState(1);
  const [loading, setLoading] = useState(true);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);

  const [restaurantId, setRestaurantId] = useState('');
  const [branchId, setBranchId] = useState('');
  const [selectedStatuses, setSelectedStatuses] = useState<string[]>([]);
  const [channel, setChannel] = useState('');
  const [deliveryType, setDeliveryType] = useState('');
  const [dateFrom, setDateFrom] = useState('');
  const [dateTo, setDateTo] = useState('');
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const [debouncedSearch, setDebouncedSearch] = useState('');

  useEffect(() => {
    fetch('/api/admin/restaurants', { credentials: 'include' })
      .then(r => r.json())
      .then(d => setRestaurants(d.restaurants ?? []))
      .catch(() => {});
  }, []);

  useEffect(() => {
    if (!restaurantId) { setBranches([]); setBranchId(''); return; }
    fetch(`/api/admin/restaurants/branches?restaurant_id=${restaurantId}`, { credentials: 'include' })
      .then(r => r.json())
      .then(d => setBranches(d.branches ?? []))
      .catch(() => {});
    setBranchId('');
  }, [restaurantId]);

  const handleSearchChange = (v: string) => {
    setSearch(v);
    setPage(1);
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => setDebouncedSearch(v), 350);
  };

  const fetchOrders = useCallback(async () => {
    setLoading(true);
    try {
      const sp = new URLSearchParams();
      if (restaurantId) sp.set('restaurant_id', restaurantId);
      if (branchId) sp.set('branch_id', branchId);
      if (selectedStatuses.length > 0) sp.set('status', selectedStatuses.join(','));
      if (channel) sp.set('channel', channel);
      if (deliveryType) sp.set('delivery_type', deliveryType);
      if (dateFrom) sp.set('date_from', dateFrom);
      if (dateTo) sp.set('date_to', dateTo);
      if (debouncedSearch) sp.set('search', debouncedSearch);
      sp.set('page', String(page));
      sp.set('limit', '25');
      const res = await fetch(`/api/admin/orders?${sp}`, { credentials: 'include' });
      const data = await res.json();
      setOrders(data.orders ?? []);
      setTotal(data.total ?? 0);
      setPages(data.pages ?? 1);
      if (data.stats) setStats(data.stats);
    } catch { /* empty */ }
    setLoading(false);
  }, [restaurantId, branchId, selectedStatuses, channel, deliveryType, dateFrom, dateTo, debouncedSearch, page]);

  useEffect(() => { fetchOrders(); }, [fetchOrders]);

  const resetFilters = () => {
    setRestaurantId(''); setBranchId(''); setSelectedStatuses([]); setChannel('');
    setDeliveryType(''); setDateFrom(''); setDateTo(''); setSearch(''); setDebouncedSearch(''); setPage(1);
  };

  const hasFilters = restaurantId || branchId || selectedStatuses.length > 0 || channel || deliveryType || dateFrom || dateTo || debouncedSearch;

  return (
    <>
      <div className="flex items-center gap-3 px-4 py-3 rounded-xl mb-6" style={{ backgroundColor: 'hsl(231, 40%, 14%)', color: 'white' }}>
        <div className="w-2 h-2 rounded-full bg-orange-400 animate-pulse" />
        <span className="text-sm font-semibold">{t('admin.title', 'Admin Panel')}</span>
        <span className="text-xs opacity-60">— {t('admin.orders.adminNote', 'Read-only view of all orders across all restaurants')}</span>
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3 mb-6">
        <StatCard icon={<ShoppingBag size={16} style={{ color: 'hsl(var(--primary))' }} />} label={t('admin.orders.totalOrders', 'Total Orders')} value={stats.total.toLocaleString()} />
        <StatCard icon={<DollarSign size={16} style={{ color: 'hsl(var(--primary))' }} />} label={t('admin.orders.revenue', 'Revenue')} value={fmt(stats.revenue)} />
        <StatCard icon={<Clock size={16} style={{ color: 'hsl(var(--primary))' }} />} label={t('admin.orders.pending', 'Pending')} value={stats.pending.toLocaleString()} />
        <StatCard icon={<Zap size={16} style={{ color: 'hsl(var(--primary))' }} />} label={t('admin.orders.active', 'Active')} value={stats.active.toLocaleString()} />
        <StatCard icon={<CheckCircle2 size={16} style={{ color: 'hsl(var(--primary))' }} />} label={t('admin.orders.completed', 'Completed')} value={stats.completed.toLocaleString()} />
        <StatCard icon={<XCircle size={16} style={{ color: 'hsl(var(--primary))' }} />} label={t('admin.orders.cancelled', 'Cancelled')} value={stats.cancelled.toLocaleString()} />
      </div>

      <div className="card p-4 mb-4 space-y-3">
        <div className="relative">
          <Search size={15} className="absolute left-3.5 top-1/2 -translate-y-1/2" style={{ color: 'hsl(var(--muted-foreground))' }} />
          <input
            className="input-base pl-10 w-full"
            placeholder={t('admin.orders.searchPlaceholder', 'Search by customer name, phone, or order number…')}
            value={search}
            onChange={e => handleSearchChange(e.target.value)}
          />
        </div>

        <div className="flex flex-wrap items-center gap-2">
          <select className="input-base text-sm h-9 py-0" value={restaurantId} onChange={e => { setRestaurantId(e.target.value); setPage(1); }}>
            <option value="">All Restaurants</option>
            {restaurants.map(r => <option key={r.id} value={r.id}>{r.name}</option>)}
          </select>

          {restaurantId && branches.length > 0 && (
            <select className="input-base text-sm h-9 py-0" value={branchId} onChange={e => { setBranchId(e.target.value); setPage(1); }}>
              <option value="">All Branches</option>
              {branches.map(b => <option key={b.id} value={b.id}>{b.name}</option>)}
            </select>
          )}

          <StatusMultiSelect
            options={ALL_ORDER_STATUSES}
            selected={selectedStatuses}
            onChange={v => { setSelectedStatuses(v); setPage(1); }}
            placeholder="All Statuses"
          />

          <div className="flex items-center rounded-lg overflow-hidden shrink-0" style={{ border: '1px solid hsl(var(--border))' }}>
            {(['', 'chat', 'voice'] as const).map((c, i) => {
              const isActive = channel === c;
              const labels: Record<string, string> = { '': 'All', chat: 'Chat', voice: 'Voice' };
              return (
                <button
                  key={c}
                  onClick={() => { setChannel(c); setPage(1); }}
                  className="h-9 px-3 text-sm font-medium transition-colors"
                  style={{
                    backgroundColor: isActive ? 'hsl(var(--primary))' : 'transparent',
                    color: isActive ? 'white' : 'hsl(var(--foreground))',
                    borderRight: i < 2 ? '1px solid hsl(var(--border))' : 'none',
                  }}
                >
                  {labels[c]}
                </button>
              );
            })}
          </div>

          <select className="input-base text-sm h-9 py-0" value={deliveryType} onChange={e => { setDeliveryType(e.target.value); setPage(1); }}>
            <option value="">All Types</option>
            <option value="dine-in">Dine In</option>
            <option value="takeaway">Takeaway</option>
            <option value="delivery">Delivery</option>
          </select>

          <div className="flex items-center gap-1.5 rounded-lg px-3 h-9 shrink-0" style={{ border: '1px solid hsl(var(--border))' }}>
            <input
              type="date"
              className="text-sm bg-transparent outline-none"
              style={{ color: dateFrom ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))', width: '120px' }}
              value={dateFrom}
              onChange={e => { setDateFrom(e.target.value); setPage(1); }}
              title="From date"
            />
            <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>—</span>
            <input
              type="date"
              className="text-sm bg-transparent outline-none"
              style={{ color: dateTo ? 'hsl(var(--foreground))' : 'hsl(var(--muted-foreground))', width: '120px' }}
              value={dateTo}
              onChange={e => { setDateTo(e.target.value); setPage(1); }}
              title="To date"
            />
          </div>

          {hasFilters && (
            <button
              className="h-9 px-3 text-sm flex items-center gap-1.5 rounded-lg transition-colors"
              style={{ color: 'hsl(var(--muted-foreground))', border: '1px solid hsl(var(--border))' }}
              onClick={resetFilters}
            >
              <X size={13} /> Clear
            </button>
          )}
        </div>
      </div>

      <div className="card overflow-hidden">
        <div className="flex items-center justify-between px-4 py-3" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
          <span className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>
            {total.toLocaleString()} {t('admin.orders.results', 'orders')}
          </span>
          {loading && <Loader2 size={16} className="animate-spin" style={{ color: 'hsl(var(--muted-foreground))' }} />}
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                {['Order #', 'Restaurant', 'Branch', 'Customer', 'Items', 'Status', 'Channel', 'Type', 'Total', 'Date'].map(h => (
                  <th key={h} className="px-4 py-2.5 text-left text-xs font-semibold whitespace-nowrap" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {loading && orders.length === 0 ? (
                <tr><td colSpan={10} className="px-4 py-12 text-center text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  <Loader2 size={20} className="animate-spin mx-auto mb-2" />Loading…
                </td></tr>
              ) : orders.length === 0 ? (
                <tr><td colSpan={10} className="px-4 py-12 text-center text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  <Package size={28} className="mx-auto mb-2 opacity-40" />
                  {t('admin.orders.noOrders', 'No orders found')}
                </td></tr>
              ) : orders.map(order => {
                const items: OrderItem[] = Array.isArray(order.items) ? order.items : [];
                return (
                  <tr
                    key={order.id}
                    className="cursor-pointer transition-colors hover:bg-black/5"
                    style={{ borderBottom: '1px solid hsl(var(--border))' }}
                    onClick={() => setSelectedOrder(order)}
                  >
                    <td className="px-4 py-3 font-mono font-semibold whitespace-nowrap" style={{ color: 'hsl(var(--primary))' }}>
                      #{order.order_number}
                    </td>
                    <td className="px-4 py-3 max-w-36 truncate" style={{ color: 'hsl(var(--foreground))' }}>
                      {order.restaurant_name ?? '—'}
                    </td>
                    <td className="px-4 py-3 max-w-28 truncate" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {order.branch_name ?? '—'}
                    </td>
                    <td className="px-4 py-3">
                      <p className="font-medium truncate max-w-32" style={{ color: 'hsl(var(--foreground))' }}>{order.customer_name ?? '—'}</p>
                      {order.customer_phone && <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{order.customer_phone}</p>}
                    </td>
                    <td className="px-4 py-3 whitespace-nowrap text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {items.length} {items.length === 1 ? 'item' : 'items'}
                    </td>
                    <td className="px-4 py-3 whitespace-nowrap">
                      <span className={`badge ${STATUS_COLORS[order.status] ?? 'badge-neutral'} capitalize`}>{order.status}</span>
                    </td>
                    <td className="px-4 py-3 whitespace-nowrap">
                      <span className={`badge ${CHANNEL_COLORS[order.channel] ?? 'badge-neutral'} capitalize`}>{order.channel}</span>
            {order.source && (SOURCE_LABELS[order.source] || order.source !== order.channel) && (
              <span className={`badge ${order.source === 'storefront' ? 'badge-warning' : 'badge-neutral'} ml-1`}>{SOURCE_LABELS[order.source] ?? order.source}</span>
            )}
                    </td>
                    <td className="px-4 py-3 whitespace-nowrap text-xs capitalize" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {order.delivery_type?.replace('-', ' ') ?? '—'}
                    </td>
                    <td className="px-4 py-3 font-semibold whitespace-nowrap" style={{ color: 'hsl(var(--foreground))' }}>
                      {fmt(order.total)}
                    </td>
                    <td className="px-4 py-3 text-xs whitespace-nowrap" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {fmtDate(order.created_at)}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {pages > 1 && (
          <div className="flex items-center justify-between px-4 py-3" style={{ borderTop: '1px solid hsl(var(--border))' }}>
            <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
              {t('admin.orders.page', 'Page')} {page} {t('admin.orders.of', 'of')} {pages}
            </span>
            <div className="flex gap-2">
              <button className="btn-secondary p-2" disabled={page <= 1} onClick={() => setPage(p => Math.max(1, p - 1))}>
                <ChevronLeft size={14} />
              </button>
              <button className="btn-secondary p-2" disabled={page >= pages} onClick={() => setPage(p => Math.min(pages, p + 1))}>
                <ChevronRight size={14} />
              </button>
            </div>
          </div>
        )}
      </div>

      {selectedOrder && (
        <OrderDrawer
          orderId={selectedOrder.id}
          listOrder={selectedOrder}
          onClose={() => setSelectedOrder(null)}
        />
      )}
    </>
  );
}
