import { useState, useEffect, useMemo } from 'react';
import { Plus, Search, Trash2 } from 'lucide-react';
import { Button } from '@astryxdesign/core/Button';
import { Card } from '@astryxdesign/core/Card';
import { Table, proportional, pixel } from '@astryxdesign/core/Table';
import { Badge } from '@astryxdesign/core/Badge';
import { Text } from '@astryxdesign/core/Text';
import { Dialog, DialogHeader } from '@astryxdesign/core/Dialog';
import { Layout, LayoutContent, LayoutFooter } from '@astryxdesign/core/Layout';
import { FormLayout } from '@astryxdesign/core/FormLayout';
import { Field } from '@astryxdesign/core/Field';
import { TextInput } from '@astryxdesign/core/TextInput';
import { NumberInput } from '@astryxdesign/core/NumberInput';
import { Selector } from '@astryxdesign/core/Selector';
import { CheckboxInput } from '@astryxdesign/core/CheckboxInput';

import PageHeader from '@/components/PageHeader';
import EmptyState from '@/components/EmptyState';
import StatusChip from '@/components/StatusChip';
import TabLabelCount from '@/components/TabLabelCount';
import TablePagination from '@/components/TablePagination';
import { fetchClients } from '@/utils/apiClient';
import ClientFormDialog from '../tenants/ClientFormDialog';

const API_BASE = import.meta.env.VITE_API_BASE || 'https://api.doormile.com/api/v1';

const CITIES = [
  'Chennai', 'Coimbatore', 'Madurai', 'Tiruchirappalli', 'Salem', 'Tuticorin', 'Tirupur', 'Erode', 'Vellore', 'Tirunelveli', 'Thanjavur', 'Dindigul', 'Hosur', 'Nagercoil', 'Karur', 'Namakkal', 'Kanchipuram', 'Cuddalore', 'Thoothukudi',
  'Bengaluru', 'Mysuru', 'Mangaluru', 'Hubli', 'Belagavi', 'Kalaburagi', 'Davangere', 'Ballari',
  'Kochi', 'Thiruvananthapuram', 'Kozhikode', 'Kannur', 'Thrissur', 'Kollam',
  'Hyderabad', 'Warangal', 'Visakhapatnam', 'Vijayawada', 'Tirupati', 'Guntur', 'Rajahmundry', 'Nellore',
  'Mumbai', 'Pune', 'Nagpur', 'Nashik', 'Aurangabad', 'Kolhapur', 'Solapur',
  'New Delhi', 'Gurugram', 'Noida', 'Faridabad', 'Chandigarh', 'Amritsar', 'Ludhiana', 'Jalandhar',
  'Ahmedabad', 'Surat', 'Vadodara', 'Rajkot', 'Bhavnagar', 'Jamnagar',
  'Kolkata', 'Howrah', 'Durgapur', 'Asansol', 'Siliguri',
  'Lucknow', 'Kanpur', 'Agra', 'Varanasi', 'Allahabad', 'Meerut',
  'Bhopal', 'Indore', 'Gwalior', 'Jabalpur',
  'Jaipur', 'Jodhpur', 'Udaipur', 'Kota', 'Bikaner',
  'Patna', 'Gaya', 'Bhagalpur',
  'Bhubaneswar', 'Cuttack', 'Rourkela',
  'Guwahati', 'Raipur', 'Ranchi', 'Dehradun'
];

const getHeaders = () => {
  const token = localStorage.getItem('auth_token');
  return {
    'Content-Type': 'application/json',
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
};

async function apiFetchBookings() {
  const res = await fetch(`${API_BASE}/admin/bookings`, { headers: getHeaders() });
  if (!res.ok) throw new Error('Failed to fetch bookings');
  const json = await res.json();
  return Array.isArray(json) ? json : (json.data || []);
}

async function apiFetchSurveys() {
  const res = await fetch(`${API_BASE}/admin/competitor-branches?limit=1000`, { headers: getHeaders() });
  if (!res.ok) throw new Error('Failed to fetch surveys');
  const json = await res.json();
  return Array.isArray(json) ? json : (json.data || []);
}

async function apiCreateBooking(payload) {
  const res = await fetch(`${API_BASE}/admin/crmbooking`, {
    method: 'POST',
    headers: getHeaders(),
    body: JSON.stringify(payload)
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.error || 'Failed to create booking');
  }
  return res.json();
}

function BookingFormDialog({ open, onClose, onSave, clients, surveys }) {
  const [clientDialogOpen, setClientDialogOpen] = useState(false);
  const [formData, setFormData] = useState({
    customer_name: '',
    customer_phone: '',
    pickupaddress: '',
    pickuppincode: '',
    deliveryaddress: '',
    deliverypincode: '',
    deliverycity: '',
    providercompany: '',
    providerlocation: '',
    notes: '',
    service_option: 'Normal',
    finalprice: '',
    insuranceamount: '',
    needsinsurance: false,
    declaredvalue: '',
    parcels: [{ itemcategory: '', weight: '', length: '', width: '', height: '' }]
  });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);
  const [quoteInfo, setQuoteInfo] = useState(null);

  useEffect(() => {
    if (open) {
      setFormData({
        customer_name: '',
        customer_phone: '',
        pickupaddress: '',
        pickuppincode: '',
        deliveryaddress: '',
        deliverypincode: '',
        deliverycity: '',
        providercompany: '',
        providerlocation: '',
        notes: '',
        service_option: 'Normal',
        finalprice: '',
        insuranceamount: '',
        needsinsurance: false,
        declaredvalue: '',
        parcels: [{ itemcategory: '', weight: '', length: '', width: '', height: '' }]
      });
      setError(null);
      setQuoteInfo(null);
    }
  }, [open]);

  const set = (field) => (val) => {
    setFormData(prev => ({ ...prev, [field]: val }));
  };

  const handleParcelChange = (index, field) => (val) => {
    const newParcels = [...formData.parcels];
    newParcels[index] = { ...newParcels[index], [field]: val };
    setFormData(prev => ({ ...prev, parcels: newParcels }));
  };

  const addParcel = () => {
    setFormData(prev => ({
      ...prev,
      parcels: [...prev.parcels, { itemcategory: '', weight: '', length: '', width: '', height: '' }]
    }));
  };

  const removeParcel = (index) => {
    if (formData.parcels.length <= 1) return;
    const newParcels = [...formData.parcels];
    newParcels.splice(index, 1);
    setFormData(prev => ({ ...prev, parcels: newParcels }));
  };

  const handleSave = async () => {
    setSaving(true);
    setError(null);
    try {
      if (!formData.pickupaddress || !formData.pickuppincode) {
        throw new Error('Pickup Address and Pincode are required');
      }

      const payload = {
        ...formData,
        finalprice: parseFloat(formData.finalprice) || 0,
        insuranceamount: parseFloat(formData.insuranceamount) || 0,
        parcels: formData.parcels.map(p => ({
          itemcategory: p.itemcategory || 'General',
          weight: parseFloat(p.weight) || 1.0,
          length: parseFloat(p.length) || 1.0,
          width: parseFloat(p.width) || 1.0,
          height: parseFloat(p.height) || 1.0,
        }))
      };

      await apiCreateBooking(payload);
      onSave();
      onClose();
    } catch (err) {
      console.error(err);
      setError(err.message || 'Failed to create booking');
    } finally {
      setSaving(false);
    }
  };

  const handleCheckPrice = async () => {
    try {
      const res = await fetch(`${API_BASE}/admin/pricing/quote`, {
        method: 'POST',
        headers: getHeaders(),
        body: JSON.stringify({
          parcels: formData.parcels.map(p => ({
            weight: parseFloat(p.weight) || 1.0,
            length: parseFloat(p.length) || 1.0,
            width: parseFloat(p.width) || 1.0,
            height: parseFloat(p.height) || 1.0,
          }))
        })
      });
      if (res.ok) {
        const data = await res.json();
        setQuoteInfo(data);
        if (!formData.finalprice) {
          setFormData(prev => ({ ...prev, finalprice: data.basequote?.toFixed(2) || '' }));
        }
      }
    } catch(e) { console.error(e); }
  };

  const uniqueProviders = Array.from(new Set(surveys.map(s => s.company).filter(Boolean)));
  const providerLocations = surveys.filter(s => s.company === formData.providercompany).map(s => s.area || s.address).filter(Boolean);
  const num = (v) => (v === '' || v == null ? undefined : Number(v));
  const setNum = (field) => (v) => set(field)(v == null ? '' : v);

  return (
    <>
      <Dialog isOpen={open} onOpenChange={(o) => { if (!o) onClose(); }} width={800} maxHeight="90dvh" purpose="form">
        <Layout
          header={<DialogHeader title="Create New Booking" onOpenChange={(o) => { if (!o) onClose(); }} />}
          content={
            <LayoutContent>
              <FormLayout>
                {error && (
                  <div style={{ padding: '12px 16px', backgroundColor: '#fef2f2', border: '1px solid #fca5a5', borderRadius: '8px', color: '#b91c1c', fontSize: '0.875rem' }}>
                    {error}
                  </div>
                )}

                {/* Customer Details */}
                <div>
                  <div style={{ fontWeight: 700, marginBottom: '8px', color: '#0A1317', fontSize: '0.9rem', textTransform: 'uppercase' }}>Customer Details</div>
                  <div style={{ display: 'flex', gap: '16px', alignItems: 'flex-end', flexWrap: 'wrap' }}>
                    <div style={{ flexGrow: 1, minWidth: '200px' }}>
                      <Field label="Select Client" inputID="booking-client-input">
                        <input
                          id="booking-client-input"
                          list="booking-clients"
                          onChange={(e) => {
                            const selected = clients.find(c => `${c.first_name || ''} ${c.last_name || ''} - ${c.phone || ''}` === e.target.value);
                            if (selected) {
                              setFormData(prev => ({
                                ...prev,
                                customer_name: `${selected.first_name || ''} ${selected.last_name || ''}`.trim(),
                                customer_phone: selected.phone || ''
                              }));
                            } else {
                              setFormData(prev => ({ ...prev, customer_name: '', customer_phone: '' }));
                            }
                          }}
                        />
                        <datalist id="booking-clients">
                          {clients.map((c) => (
                            <option key={c.id} value={`${c.first_name || ''} ${c.last_name || ''} - ${c.phone || ''}`} />
                          ))}
                        </datalist>
                      </Field>
                    </div>
                    <Button variant="secondary" icon={<Plus size={14} />} onClick={() => setClientDialogOpen(true)} label="New Client" />
                  </div>
                </div>

                {/* Assigned Provider */}
                <div>
                  <div style={{ fontWeight: 700, marginBottom: '8px', color: '#0A1317', fontSize: '0.9rem', textTransform: 'uppercase' }}>Assigned Provider (From Survey)</div>
                  <FormLayout direction="horizontal">
                    <Selector
                      label="Provider Name" placeholder="Select Provider" hasClear
                      options={uniqueProviders}
                      value={formData.providercompany}
                      onChange={(v) => setFormData(prev => ({ ...prev, providercompany: v ?? '', providerlocation: '' }))}
                    />
                    <Selector
                      label="Provider Location / Sub Hub" placeholder="Select Location" hasClear
                      options={providerLocations}
                      value={formData.providerlocation}
                      onChange={(v) => set('providerlocation')(v ?? '')}
                      isDisabled={!formData.providercompany}
                    />
                  </FormLayout>
                </div>

                {/* Pickup Location */}
                <div>
                  <div style={{ fontWeight: 700, marginBottom: '8px', color: '#0A1317', fontSize: '0.9rem', textTransform: 'uppercase' }}>Pickup Location</div>
                  <FormLayout direction="horizontal">
                    <TextInput label="Pickup Address" isRequired value={formData.pickupaddress} onChange={set('pickupaddress')} />
                    <TextInput label="Pickup Pincode" isRequired value={formData.pickuppincode} onChange={set('pickuppincode')} />
                  </FormLayout>
                </div>

                {/* Delivery Destination */}
                <div>
                  <div style={{ fontWeight: 700, marginBottom: '8px', color: '#0A1317', fontSize: '0.9rem', textTransform: 'uppercase' }}>Delivery Destination</div>
                  <FormLayout>
                    <TextInput label="Delivery Address" value={formData.deliveryaddress} onChange={set('deliveryaddress')} />
                    <FormLayout direction="horizontal">
                      <Field label="City" inputID="delivery-city-input">
                        <input id="delivery-city-input" list="delivery-cities" value={formData.deliverycity} onChange={(e) => set('deliverycity')(e.target.value)} />
                        <datalist id="delivery-cities">
                          {CITIES.map((c) => <option key={c} value={c} />)}
                        </datalist>
                      </Field>
                      <TextInput label="Delivery Pincode" value={formData.deliverypincode} onChange={set('deliverypincode')} />
                    </FormLayout>
                  </FormLayout>
                </div>

                {/* Parcel Details */}
                <div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
                    <div style={{ fontWeight: 700, color: '#0A1317', fontSize: '0.9rem', textTransform: 'uppercase' }}>Parcel Details</div>
                    <Button variant="secondary" size="sm" icon={<Plus size={12} />} onClick={addParcel} label="Add Parcel" />
                  </div>

                  {formData.parcels.map((parcel, idx) => (
                    <div style={{ display: 'flex', gap: '12px', alignItems: 'flex-end', marginBottom: '12px', flexWrap: 'wrap' }} key={idx}>
                      <div style={{ flex: '1 1 150px' }}>
                        <TextInput label="Category" isLabelHidden placeholder="Category (e.g. Box)" value={parcel.itemcategory} onChange={handleParcelChange(idx, 'itemcategory')} />
                      </div>
                      <div style={{ width: '90px' }}>
                        <NumberInput label="Weight (kg)" isLabelHidden placeholder="Wt (kg)" hasClear value={num(parcel.weight)} onChange={(v) => handleParcelChange(idx, 'weight')(v == null ? '' : v)} />
                      </div>
                      <div style={{ width: '90px' }}>
                        <NumberInput label="Length (cm)" isLabelHidden placeholder="L (cm)" hasClear value={num(parcel.length)} onChange={(v) => handleParcelChange(idx, 'length')(v == null ? '' : v)} />
                      </div>
                      <div style={{ width: '90px' }}>
                        <NumberInput label="Width (cm)" isLabelHidden placeholder="W (cm)" hasClear value={num(parcel.width)} onChange={(v) => handleParcelChange(idx, 'width')(v == null ? '' : v)} />
                      </div>
                      <div style={{ width: '90px' }}>
                        <NumberInput label="Height (cm)" isLabelHidden placeholder="H (cm)" hasClear value={num(parcel.height)} onChange={(v) => handleParcelChange(idx, 'height')(v == null ? '' : v)} />
                      </div>
                      <button
                        onClick={() => removeParcel(idx)}
                        disabled={formData.parcels.length === 1}
                        style={{
                          background: 'none',
                          border: 'none',
                          cursor: 'pointer',
                          color: '#dc2626',
                          display: 'flex',
                          padding: '9px',
                          borderRadius: '4px'
                        }}
                        className="action-btn"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  ))}
                </div>

                {/* Price & Insurance */}
                <div>
                  <div style={{ display: 'flex', gap: '12px', alignItems: 'center', marginBottom: '12px', flexWrap: 'wrap' }}>
                    <div style={{ fontWeight: 700, color: '#0A1317', fontSize: '0.9rem', textTransform: 'uppercase' }}>Price & Insurance</div>
                    <Button variant="secondary" size="sm" onClick={handleCheckPrice} label="Check Price Estimate" />
                  </div>
                  {quoteInfo && (
                    <div style={{ padding: '12px', borderLeft: '4px solid #3b82f6', backgroundColor: '#eff6ff', fontSize: '0.875rem', marginBottom: '16px', color: '#1e3a8a' }}>
                      Estimated Base Price: <strong>₹{quoteInfo.basequote?.toFixed(2)}</strong> (Chargeable Weight: {quoteInfo.chargeableweight} kg)
                    </div>
                  )}
                  <FormLayout direction="horizontal">
                    <NumberInput label="Final Price (₹)" hasClear value={num(formData.finalprice)} onChange={setNum('finalprice')} />
                    <div>
                      <CheckboxInput
                        label="Needs Insurance? (1%)"
                        value={formData.needsinsurance}
                        onChange={(checked) => {
                          setFormData(prev => ({
                            ...prev,
                            needsinsurance: checked,
                            insuranceamount: checked && prev.declaredvalue ? (parseFloat(prev.declaredvalue) * 0.01).toFixed(2) : prev.insuranceamount
                          }));
                        }}
                      />
                    </div>
                    <NumberInput
                      label="Declared Value" hasClear value={num(formData.declaredvalue)}
                      onChange={(v) => {
                        setFormData(prev => ({
                          ...prev,
                          declaredvalue: v == null ? '' : v,
                          insuranceamount: prev.needsinsurance && v != null ? (v * 0.01).toFixed(2) : prev.insuranceamount
                        }));
                      }}
                    />
                    <NumberInput label="Insurance Amount" hasClear value={num(formData.insuranceamount)} onChange={setNum('insuranceamount')} />
                  </FormLayout>
                </div>

                {/* Additional info */}
                <div>
                  <div style={{ fontWeight: 700, marginBottom: '8px', color: '#0A1317', fontSize: '0.9rem', textTransform: 'uppercase' }}>Additional Information</div>
                  <FormLayout direction="horizontal">
                    <Selector
                      label="Select Speed"
                      options={[{ value: 'Normal', label: 'Normal' }, { value: 'Fast', label: 'Fast Express' }]}
                      value={formData.service_option}
                      onChange={set('service_option')}
                    />
                    <TextInput label="Notes / Remarks" value={formData.notes} onChange={set('notes')} />
                  </FormLayout>
                </div>
              </FormLayout>
            </LayoutContent>
          }
          footer={
            <LayoutFooter hasDivider>
              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '12px' }}>
                <Button label="Cancel" variant="ghost" onClick={onClose} isDisabled={saving} />
                <Button
                  label={saving ? 'Creating...' : 'Create Booking'}
                  variant="primary"
                  onClick={handleSave}
                  isDisabled={saving || !formData.customer_phone}
                  isLoading={saving}
                />
              </div>
            </LayoutFooter>
          }
        />
      </Dialog>

      {clientDialogOpen && (
        <ClientFormDialog
          open={clientDialogOpen}
          mode="create"
          onClose={() => setClientDialogOpen(false)}
          onSaved={() => {
            setClientDialogOpen(false);
            onSave();
          }}
        />
      )}
    </>
  );
}

export default function Bookings() {
  const [bookings, setBookings] = useState([]);
  const [clients, setClients] = useState([]);
  const [surveys, setSurveys] = useState([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [sourceFilter, setSourceFilter] = useState('All');
  const [formOpen, setFormOpen] = useState(false);
  const [page, setPage] = useState(0);
  const [rpp, setRpp] = useState(10);

  const loadData = async () => {
    setLoading(true);
    try {
      const [bookingsData, clientsData, surveysData] = await Promise.all([
        apiFetchBookings(),
        fetchClients().catch(() => []),
        apiFetchSurveys().catch(() => [])
      ]);
      setBookings(Array.isArray(bookingsData) ? bookingsData : []);
      setClients(Array.isArray(clientsData) ? clientsData : []);
      setSurveys(Array.isArray(surveysData) ? surveysData : []);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

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

  const displayBookings = bookings.filter(b => {
    const matchesSearch = (b.bookingno || '').toLowerCase().includes(search.toLowerCase()) ||
                          (b.pickupaddress || '').toLowerCase().includes(search.toLowerCase()) ||
                          (b.deliverycity || '').toLowerCase().includes(search.toLowerCase()) ||
                          (b.providercompany || '').toLowerCase().includes(search.toLowerCase());
    const matchesSource = sourceFilter === 'All' || b.bookingsource === sourceFilter;
    return matchesSearch && matchesSource;
  });

  const pagedBookings = displayBookings.slice(page * rpp, page * rpp + rpp);

  const bookingColumns = useMemo(() => [
    {
      key: 'bookingno',
      header: <div style={{ paddingLeft: '12px' }}>Booking No</div>,
      width: proportional(1.5),
      renderCell: (b) => (
        <div style={{ paddingLeft: '12px' }}>
          <Text type="body" weight="semibold">{b.bookingno}</Text>
        </div>
      )
    },
    {
      key: 'deliverycity',
      header: 'Delivery City',
      width: proportional(1),
      renderCell: (b) => {
        const city = b.deliverycity || b.deliverypincode;
        return city
          ? <Text type="body">{city}</Text>
          : <Text type="supporting" color="disabled">N/A</Text>;
      }
    },
    {
      key: 'providercompany',
      header: 'Provider',
      width: proportional(1),
      renderCell: (b) => b.providercompany
        ? <Badge variant="neutral" label={b.providercompany} />
        : <Text type="supporting" color="disabled">N/A</Text>
    },
    {
      key: 'bookingsource',
      header: 'Source',
      width: pixel(100),
      renderCell: (b) => (
        <Badge
          variant={b.bookingsource === 'CRM_Console' ? 'neutral' : 'red'}
          label={b.bookingsource === 'CRM_Console' ? 'CRM' : 'App'}
        />
      )
    },
    {
      key: 'price',
      header: 'Price',
      width: pixel(120),
      renderCell: (b) => (
        <Text type="body" weight="semibold" hasTabularNumbers>
          {b.serviceoptions && b.serviceoptions.length > 0 ? `₹${b.serviceoptions[0].estimatedprice}` : 'N/A'}
        </Text>
      )
    },
    {
      key: 'status',
      header: 'Status',
      width: pixel(150),
      renderCell: (b) => <StatusChip status={b.status} />
    }
  ], []);

  const sourceCounts = useMemo(() => {
    const counts = { All: bookings.length, Customer_App: 0, CRM_Console: 0 };
    bookings.forEach((b) => {
      if (b.bookingsource === 'CRM_Console') counts.CRM_Console += 1;
      else counts.Customer_App += 1;
    });
    return counts;
  }, [bookings]);

  return (
    <div style={{ fontFamily: 'system-ui, sans-serif' }}>
      <PageHeader
        title="Bookings Management"
        action={
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'nowrap' }}>
            <div style={{ flex: '0 1 320px', minWidth: '200px' }}>
              <TextInput
                label="Search bookings"
                isLabelHidden
                placeholder="Search bookings…"
                startIcon={<Search size={16} />}
                hasClear
                value={search}
                onChange={(v) => { setSearch(v); setPage(0); }}
              />
            </div>
            <Button variant="primary" icon={<Plus size={14} />} onClick={() => setFormOpen(true)} label="New Booking" style={{ flexShrink: 0 }} />
          </div>
        }
      />

      <Card style={{ marginTop: '24px', padding: '0', borderRadius: '16px', border: '1px solid rgba(5, 54, 89, 0.08)', backgroundColor: '#ffffff', overflow: 'hidden', boxShadow: '0 10px 30px -5px rgba(0,0,0,0.02), 0 4px 12px -3px rgba(0,0,0,0.02)' }}>
        {/* Tab filters */}
        <div style={{ display: 'flex', padding: '0 24px', borderBottom: '1px solid rgba(5, 54, 89, 0.06)', gap: '24px', overflowX: 'auto' }}>
          {[
            { label: 'All Bookings', value: 'All' },
            { label: 'App Bookings', value: 'Customer_App' },
            { label: 'CRM Bookings', value: 'CRM_Console' }
          ].map((tab) => (
            <div
              key={tab.value}
              onClick={() => { setSourceFilter(tab.value); setPage(0); }}
              style={{
                padding: '16px 0',
                cursor: 'pointer',
                borderBottom: sourceFilter === tab.value ? '2px solid #0A1317' : '2px solid transparent',
                color: sourceFilter === tab.value ? '#0A1317' : '#64748b',
                fontWeight: sourceFilter === tab.value ? 600 : 500,
                fontSize: '0.875rem',
                transition: 'all 0.2s'
              }}
            >
              <TabLabelCount label={tab.label} count={sourceCounts[tab.value] || 0} active={sourceFilter === tab.value} />
            </div>
          ))}
        </div>

        {loading ? (
          <div style={{ display: 'flex', justifyContent: 'center', padding: '48px 0' }}>
            <div className="spinner" style={{ width: '32px', height: '32px', border: '3px solid #f1f5f9', borderTop: '3px solid #0A1317', borderRadius: '50%', animation: 'spin 1s linear infinite' }} />
          </div>
        ) : displayBookings.length === 0 ? (
          <EmptyState title="No bookings found" caption="Try a different filter or search term, or create a new booking." />
        ) : (
          <div style={{ paddingTop: '12px', paddingBottom: '12px' }}>
            <Table
              data={pagedBookings}
              columns={bookingColumns}
              idKey="bookingid"
              density="balanced"
              dividers="rows"
              hasHover
              isStriped
              textOverflow="truncate"
            />
          </div>
        )}

        {!loading && displayBookings.length > 0 && (
          <TablePagination page={page} rpp={rpp} total={displayBookings.length} onPageChange={setPage} onRppChange={setRpp} />
        )}
      </Card>

      <BookingFormDialog 
        open={formOpen} 
        onClose={() => setFormOpen(false)} 
        onSave={() => { loadData(); }}
        clients={clients}
        surveys={surveys}
      />
      <style>{`
        .action-btn:hover {
          background-color: #f1f5f9;
        }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}

const inputStyle = {
  width: '100%',
  padding: '8px 12px',
  borderRadius: '6px',
  border: '1px solid #cbd5e1',
  fontSize: '0.875rem',
  color: '#1e293b',
  outline: 'none',
  boxSizing: 'border-box',
  transition: 'border-color 0.2s',
  backgroundColor: '#ffffff'
};

const selectStyle = {
  ...inputStyle,
  height: '38px',
  cursor: 'pointer'
};
