'use client';

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

interface Booking {
  id: string;
  restaurant_id: string;
  restaurant_name: string;
  branch_id: string | null;
  branch_name: string | null;
  customer_id: string | null;
  customer_full_name: string | null;
  customer_full_email: string | null;
  guest_name: string;
  guest_phone: string | null;
  guest_email: string | null;
  is_vip: boolean;
  booking_date: string | null;
  booking_time: string | null;
  party_size: number;
  table_no: string | null;
  zone: string | null;
  status: string;
  channel: string;
  occasion: string | null;
  dietary_needs: string[] | string;
  special_requests: string | null;
  ai_notes: string | null;
  ai_confidence: number | null;
  reminder_sent: boolean;
  notes: string | null;
  agent_id: string | null;
  conversation_id: string | null;
  created_at: string;
  updated_at: string;
}

interface Stats {
  total: number;
  today: number;
  confirmed: number;
  seated: number;
  cancelled: number;
  noshow: number;
  pending: number;
}

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

const ALL_BOOKING_STATUSES = ['pending','confirmed','seated','completed','cancelled','noshow','escalated','reminder_sent'];

const STATUS_COLORS: Record<string, string> = {
  pending: 'badge-warning',
  confirmed: 'badge-primary',
  seated: 'badge-success',
  completed: 'badge-success',
  cancelled: 'badge-danger',
  noshow: 'badge-danger',
  escalated: 'badge-danger',
  reminder_sent: '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',
};

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

function fmtBookingDate(date: string | null, time: string | null) {
  if (!date) return '—';
  const d = new Date(date + 'T00:00:00').toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
  return time ? `${d} ${time}` : d;
}

function parseDietary(val: string[] | string): string[] {
  if (Array.isArray(val)) return val;
  try { return JSON.parse(val as string) as string[]; } catch { return []; }
}

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].replace('_', ' ')
      : `${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 capitalize" 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: '180px' }}>
          {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.replace('_', ' ')}
            </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 BookingDrawer({ bookingId, listBooking, onClose }: { bookingId: string; listBooking: Booking; onClose: () => void }) {
  const { t } = useLanguage();
  const [booking, setBooking] = useState<Booking>(listBooking);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(`/api/admin/bookings/${bookingId}`, { credentials: 'include' })
      .then(r => r.json())
      .then(d => { if (d.booking) setBooking(d.booking as Booking); })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, [bookingId]);

  const dietary = parseDietary(booking.dietary_needs);
  const displayName = booking.customer_full_name ?? booking.guest_name;

  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 className="flex items-center gap-2">
            <h3 className="font-bold text-base" style={{ color: 'hsl(var(--foreground))' }}>{booking.guest_name}</h3>
            {booking.is_vip && (
              <span className="flex items-center gap-1 badge badge-warning text-xs">
                <Star size={10} fill="currentColor" />VIP
              </span>
            )}
          </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[booking.status] ?? 'badge-neutral'} capitalize`}>{booking.status.replace('_', ' ')}</span>
            <span className={`badge ${CHANNEL_COLORS[booking.channel] ?? 'badge-neutral'} capitalize`}>{booking.channel}</span>
            {booking.reminder_sent && <span className="badge badge-info">Reminder Sent</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.bookings.restaurant', 'Restaurant')}</p>
            <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{booking.restaurant_name ?? '—'}</p>
            {booking.branch_name && <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{booking.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.bookings.guest', 'Guest')}</p>
            <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{displayName}</p>
            {booking.guest_phone && <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{booking.guest_phone}</p>}
            {(booking.customer_full_email ?? booking.guest_email) && (
              <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{booking.customer_full_email ?? booking.guest_email}</p>
            )}
          </div>

          <div className="rounded-xl p-4" style={{ border: '1px solid hsl(var(--border))' }}>
            <p className="text-xs font-semibold mb-3" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.bookings.reservationDetails', 'Reservation Details')}</p>
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div>
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.bookings.dateTime', 'Date & Time')}</p>
                <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{fmtBookingDate(booking.booking_date, booking.booking_time)}</p>
              </div>
              <div>
                <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.bookings.partySize', 'Party Size')}</p>
                <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{booking.party_size} {t('admin.bookings.guests', 'guests')}</p>
              </div>
              {booking.table_no && (
                <div>
                  <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.bookings.table', 'Table')}</p>
                  <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>#{booking.table_no}</p>
                </div>
              )}
              {booking.zone && (
                <div>
                  <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.bookings.zone', 'Zone')}</p>
                  <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{booking.zone}</p>
                </div>
              )}
              {booking.occasion && (
                <div className="col-span-2">
                  <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.bookings.occasion', 'Occasion')}</p>
                  <p className="font-medium text-sm capitalize" style={{ color: 'hsl(var(--foreground))' }}>{booking.occasion}</p>
                </div>
              )}
            </div>
          </div>

          {dietary.length > 0 && (
            <div className="rounded-xl p-4" style={{ border: '1px solid hsl(var(--border))' }}>
              <p className="text-xs font-semibold mb-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('admin.bookings.dietaryNeeds', 'Dietary Needs')}</p>
              <div className="flex flex-wrap gap-1.5">
                {dietary.map((d, i) => <span key={i} className="badge badge-neutral text-xs">{d}</span>)}
              </div>
            </div>
          )}

          {booking.special_requests && (
            <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.bookings.specialRequests', 'Special Requests')}</p>
              <p className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>{booking.special_requests}</p>
            </div>
          )}

          {booking.notes && (
            <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.bookings.notes', 'Notes')}</p>
              <p className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>{booking.notes}</p>
            </div>
          )}

          {booking.ai_notes && (
            <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(--primary))' }}>{t('admin.bookings.aiNotes', 'AI Notes')}</p>
              <p className="text-sm" style={{ color: 'hsl(var(--foreground))' }}>{booking.ai_notes}</p>
              {booking.ai_confidence != null && (
                <p className="text-xs mt-1.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                  {t('admin.bookings.confidence', 'Confidence')}: {Math.round(booking.ai_confidence * 100)}%
                </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.bookings.metadata', 'Metadata')}</p>
            {booking.agent_id && <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>Agent: <span style={{ color: 'hsl(var(--foreground))' }} className="font-mono">{booking.agent_id}</span></p>}
            {booking.conversation_id && <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>Conversation: <span style={{ color: 'hsl(var(--foreground))' }} className="font-mono">{booking.conversation_id.slice(0, 16)}…</span></p>}
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>Created: <span style={{ color: 'hsl(var(--foreground))' }}>{fmtDate(booking.created_at)}</span></p>
            <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>Updated: <span style={{ color: 'hsl(var(--foreground))' }}>{fmtDate(booking.updated_at)}</span></p>
            <p className="text-xs font-mono break-all" style={{ color: 'hsl(var(--muted-foreground))' }}>ID: {booking.id}</p>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function AdminBookingsPage() {
  const { t } = useLanguage();
  usePageHeader(
    t('admin.bookings.pageTitle', 'Table Bookings'),
    t('admin.bookings.pageDesc', 'All reservations across every restaurant and branch')
  );

  const [bookings, setBookings] = useState<Booking[]>([]);
  const [stats, setStats] = useState<Stats>({ total: 0, today: 0, confirmed: 0, seated: 0, cancelled: 0, noshow: 0, pending: 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 [selectedBooking, setSelectedBooking] = useState<Booking | null>(null);

  const [restaurantId, setRestaurantId] = useState('');
  const [branchId, setBranchId] = useState('');
  const [selectedStatuses, setSelectedStatuses] = useState<string[]>([]);
  const [channel, setChannel] = 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 fetchBookings = 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 (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/bookings?${sp}`, { credentials: 'include' });
      const data = await res.json();
      setBookings(data.bookings ?? []);
      setTotal(data.total ?? 0);
      setPages(data.pages ?? 1);
      if (data.stats) setStats(data.stats);
    } catch { /* empty */ }
    setLoading(false);
  }, [restaurantId, branchId, selectedStatuses, channel, dateFrom, dateTo, debouncedSearch, page]);

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

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

  const hasFilters = restaurantId || branchId || selectedStatuses.length > 0 || channel || 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.bookings.adminNote', 'Read-only view of all table bookings across all restaurants')}</span>
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7 gap-3 mb-6">
        <StatCard icon={<CalendarCheck size={16} style={{ color: 'hsl(var(--primary))' }} />} label={t('admin.bookings.total', 'Total')} value={stats.total.toLocaleString()} />
        <StatCard icon={<Clock size={16} style={{ color: 'hsl(var(--primary))' }} />} label={t('admin.bookings.today', 'Today')} value={stats.today.toLocaleString()} />
        <StatCard icon={<Clock size={16} style={{ color: 'hsl(var(--primary))' }} />} label={t('admin.bookings.pending', 'Pending')} value={stats.pending.toLocaleString()} />
        <StatCard icon={<CheckCircle2 size={16} style={{ color: 'hsl(var(--primary))' }} />} label={t('admin.bookings.confirmed', 'Confirmed')} value={stats.confirmed.toLocaleString()} />
        <StatCard icon={<Users size={16} style={{ color: 'hsl(var(--primary))' }} />} label={t('admin.bookings.seated', 'Seated')} value={stats.seated.toLocaleString()} />
        <StatCard icon={<XCircle size={16} style={{ color: 'hsl(var(--primary))' }} />} label={t('admin.bookings.cancelled', 'Cancelled')} value={stats.cancelled.toLocaleString()} />
        <StatCard icon={<CalendarX size={16} style={{ color: 'hsl(var(--primary))' }} />} label={t('admin.bookings.noShow', 'No-shows')} value={stats.noshow.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.bookings.searchPlaceholder', 'Search by guest name, phone, or email…')}
            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_BOOKING_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>

          <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.bookings.results', 'bookings')}
          </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))' }}>
                {['Guest', 'Restaurant', 'Branch', 'Date & Time', 'Party', 'Table', 'Zone', 'Occasion', 'Status', 'Channel'].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 && bookings.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>
              ) : bookings.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.bookings.noBookings', 'No bookings found')}
                </td></tr>
              ) : bookings.map(booking => (
                <tr
                  key={booking.id}
                  className="cursor-pointer transition-colors hover:bg-black/5"
                  style={{ borderBottom: '1px solid hsl(var(--border))' }}
                  onClick={() => setSelectedBooking(booking)}
                >
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-1.5">
                      <div>
                        <p className="font-medium whitespace-nowrap" style={{ color: 'hsl(var(--foreground))' }}>{booking.guest_name}</p>
                        {booking.guest_phone && <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{booking.guest_phone}</p>}
                      </div>
                      {booking.is_vip && (
                        <Star size={12} style={{ color: 'hsl(var(--warning))' }} fill="currentColor" className="shrink-0" />
                      )}
                    </div>
                  </td>
                  <td className="px-4 py-3 max-w-36 truncate" style={{ color: 'hsl(var(--foreground))' }}>
                    {booking.restaurant_name ?? '—'}
                  </td>
                  <td className="px-4 py-3 max-w-28 truncate" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {booking.branch_name ?? '—'}
                  </td>
                  <td className="px-4 py-3 whitespace-nowrap text-xs" style={{ color: 'hsl(var(--foreground))' }}>
                    {fmtBookingDate(booking.booking_date, booking.booking_time)}
                  </td>
                  <td className="px-4 py-3 text-center text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {booking.party_size}
                  </td>
                  <td className="px-4 py-3 text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {booking.table_no ?? '—'}
                  </td>
                  <td className="px-4 py-3 text-xs whitespace-nowrap" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {booking.zone ?? '—'}
                  </td>
                  <td className="px-4 py-3 text-xs capitalize" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {booking.occasion ?? '—'}
                  </td>
                  <td className="px-4 py-3 whitespace-nowrap">
                    <span className={`badge ${STATUS_COLORS[booking.status] ?? 'badge-neutral'} capitalize`}>
                      {booking.status.replace('_', ' ')}
                    </span>
                  </td>
                  <td className="px-4 py-3 whitespace-nowrap">
                    <span className={`badge ${CHANNEL_COLORS[booking.channel] ?? 'badge-neutral'} capitalize`}>
                      {booking.channel}
                    </span>
                  </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.bookings.page', 'Page')} {page} {t('admin.bookings.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>

      {selectedBooking && (
        <BookingDrawer
          bookingId={selectedBooking.id}
          listBooking={selectedBooking}
          onClose={() => setSelectedBooking(null)}
        />
      )}
    </>
  );
}
