import { useState, useMemo, useEffect, Fragment } from 'react';
import { useSearchParams } from 'react-router-dom';
import dayjs from 'dayjs';
import {
  Search,
  Plus,
  Edit,
  Trash2,
  ChevronDown,
  ChevronUp,
  Building2,
  UserPlus,
  Package,
  Handshake,
  Phone,
  MapPin,
  Truck,
  Store,
  Info,
  StickyNote,
  ArrowRight,
  Map,
  Contact
} from 'lucide-react';
import { Button } from '@astryxdesign/core/Button';
import { Card } from '@astryxdesign/core/Card';
import { Table, TableHeader, TableBody, TableRow, TableHeaderCell, TableCell } from '@astryxdesign/core/Table';
import { AlertDialog } from '@astryxdesign/core/AlertDialog';
import { TextInput } from '@astryxdesign/core/TextInput';

import PageHeader from '@/components/PageHeader';
import StatCard from '@/components/StatCard';
import StatusChip from '@/components/StatusChip';
import EmptyState from '@/components/EmptyState';
import UserAvatar from '@/components/UserAvatar';
import TabLabelCount from '@/components/TabLabelCount';
import TablePagination from '@/components/TablePagination';
import { fetchClients, deleteClient } from '@/utils/apiClient';
import { toClient } from '@/utils/mappers';
import { titleCase } from '@/utils/format';
import ClientFormDialog from './ClientFormDialog';

const consentTone = (v) => ({ full: 'success', basiconly: 'info', none: 'neutral' }[String(v || '').toLowerCase()] || 'neutral');
const efficiencyTone = (v) => {
  const k = String(v || '').toLowerCase();
  if (/high|good|excellent/.test(k)) return 'success';
  if (/med|average|moderate/.test(k)) return 'warning';
  if (/low|poor|bad/.test(k)) return 'error';
  return 'info';
};

function Pill({ label, color = 'neutral' }) {
  if (label === undefined || label === null || label === '') {
    return <span style={{ fontWeight: 500, color: '#94a3b8' }}>—</span>;
  }

  // Soft badge styling mapping
  const badgeStyles = {
    success: { bg: '#E3F6EC', fg: '#00773B' },
    warning: { bg: '#FFF7E0', fg: '#8A6500' },
    info: { bg: '#E0F7F8', fg: '#00727B' },
    error: { bg: '#FEEAE9', fg: '#A82216' },
    primary: { bg: '#F8E0E3', fg: '#9E0E20' },
    neutral: { bg: '#f1f5f9', fg: '#475569' }
  };

  const style = badgeStyles[color] || badgeStyles.neutral;

  return (
    <span
      style={{
        display: 'inline-block',
        padding: '2px 8px',
        borderRadius: '9999px',
        fontSize: '0.75rem',
        fontWeight: 600,
        backgroundColor: style.bg,
        color: style.fg
      }}
    >
      {label}
    </span>
  );
}

function Field({ label, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
      <span style={{ textTransform: 'uppercase', letterSpacing: '0.05em', fontSize: '0.68rem', fontWeight: 700, color: '#475569' }}>{label}</span>
      <div>{children}</div>
    </div>
  );
}

function ReadField({ label, value }) {
  return (
    <Field label={label}>
      <span style={{ fontWeight: 500, color: value ? '#1e293b' : '#94a3b8', fontSize: '0.875rem', wordBreak: 'break-word' }}>
        {value || '—'}
      </span>
    </Field>
  );
}

function SectionCard({ icon: Icon, title, accent = 'primary', children }) {
  return (
    <div style={{ height: '100%', borderRadius: '8px', border: '1px solid #e2e8f0', backgroundColor: '#ffffff', overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: '8px', padding: '10px 16px', borderBottom: '1px solid #e2e8f0', backgroundColor: 'rgba(10, 19, 23, 0.04)' }}>
        <Icon size={16} style={{ color: '#0A1317' }} />
        <span style={{ fontWeight: 700, color: '#1e293b', fontSize: '0.68rem', letterSpacing: '0.05em', textTransform: 'uppercase' }}>{title}</span>
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: '14px', padding: '16px' }}>{children}</div>
    </div>
  );
}

function StatTile({ label, value, icon: Icon }) {
  return (
    <div style={{ flex: 1, padding: '12px', borderRadius: '6px', border: '1px solid #e2e8f0', backgroundColor: '#f8fafc', display: 'flex', alignItems: 'center', gap: '8px' }}>
      <div style={{ width: '32px', height: '32px', borderRadius: '4px', backgroundColor: 'rgba(10, 19, 23, 0.08)', color: '#0A1317', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon size={16} />
      </div>
      <div>
        <div style={{ fontWeight: 700, color: '#1e293b', fontSize: '1.125rem', lineHeight: 1.1 }}>{value}</div>
        <div style={{ fontSize: '0.75rem', color: '#64748b' }}>{label}</div>
      </div>
    </div>
  );
}

function Metric({ label, value, color = '#1e293b' }) {
  return (
    <div style={{ textAlign: 'center', minWidth: '56px' }}>
      <div style={{ fontWeight: 700, color, fontSize: '0.875rem', lineHeight: 1.2 }}>{value}</div>
      <div style={{ color: '#64748b', fontSize: '0.65rem' }}>{label}</div>
    </div>
  );
}

function ClientDetail({ row, onEdit }) {
  return (
    <div style={{ margin: '16px', borderRadius: '10px', border: '1px solid #e2e8f0', overflow: 'hidden', boxShadow: '0 4px 16px rgba(0,0,0,0.04)', backgroundColor: '#ffffff', fontFamily: 'system-ui, sans-serif' }}>
      <div
        style={{
          display: 'flex',
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
          padding: '14px 20px',
          borderBottom: '1px solid #e2e8f0',
          background: 'linear-gradient(90deg, rgba(10, 19, 23, 0.05) 0%, #ffffff 75%)',
          flexWrap: 'wrap',
          gap: '12px'
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
          <UserAvatar name={row.name} size={40} />
          <div>
            <div style={{ fontWeight: 700, fontSize: '1rem', color: '#1e293b', lineHeight: 1.2 }}>{row.name}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '4px', marginTop: '2px', color: '#64748b', fontSize: '0.75rem' }}>
              <Contact size={12} />
              <span>{row.clientId}</span>
            </div>
          </div>
          <StatusChip status={row.status} />
        </div>
        <Button size="sm" variant="secondary" icon={<Edit size={14} />} onClick={() => onEdit(row)} label="Edit Client" />
      </div>

      <div style={{ padding: '20px', backgroundColor: '#f8fafc' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: '20px' }}>
          <SectionCard icon={Store} title="Business" accent="primary">
            <div style={{ display: 'flex', gap: '12px' }}>
              <StatTile label="Parcel Volume" value={Number(row.parcelVolume).toLocaleString()} icon={Package} />
              <StatTile label="Active Contracts" value={row.activeContracts} icon={Handshake} />
            </div>
            <Field label="Client ID">
              <span style={{ fontFamily: 'monospace', fontWeight: 600, color: '#1e293b', fontSize: '0.875rem' }}>{row.clientId}</span>
            </Field>
            <Field label="Business Type"><Pill label={row.businessType && titleCase(row.businessType)} color="primary" /></Field>
            <Field label="Order Frequency"><Pill label={row.frequency && titleCase(row.frequency)} color="info" /></Field>
          </SectionCard>

          <SectionCard icon={Truck} title="Logistics" accent="primary">
            <Field label="Logistics Segment">
              {row.logisticsSegment ? (
                <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                  {String(row.logisticsSegment).split(/[,/]/).map((seg) => seg.trim()).filter(Boolean).map((seg) => (
                    <Pill key={seg} label={titleCase(seg)} color="primary" />
                  ))}
                </div>
              ) : <Pill label={null} />}
            </Field>
            <ReadField label="Current Provider" value={row.provider} />
            <Field label="Efficiency"><Pill label={row.efficiency && titleCase(row.efficiency)} color={efficiencyTone(row.efficiency)} /></Field>
            <Field label="Transit Route">
              {(() => {
                const stops = [row.transitFrom, ...String(row.transitTo || '').split(',')]
                  .map((s) => s.trim()).filter(Boolean);
                if (!stops.length) return <Pill label={null} />;
                return (
                  <div style={{ display: 'flex', gap: '6px', alignItems: 'center', flexWrap: 'wrap' }}>
                    {stops.map((stop, idx) => (
                      <Fragment key={`${stop}-${idx}`}>
                        {idx > 0 && <ArrowRight size={14} style={{ color: '#0A1317' }} />}
                        <Pill label={titleCase(stop)} color={idx === 0 ? 'neutral' : 'info'} />
                      </Fragment>
                    ))}
                  </div>
                );
              })()}
            </Field>
          </SectionCard>

          <SectionCard icon={MapPin} title="Location & Survey" accent="primary">
            <Field label="City / State">
              <span style={{ fontWeight: 500, color: '#1e293b', fontSize: '0.875rem' }}>{[row.city, row.businessState].filter(Boolean).join(', ') || '—'}</span>
            </Field>
            <ReadField label="Neighbourhood" value={row.neighbourhood} />
            <Field label="Survey Address">
              <div style={{ display: 'flex', gap: '8px', padding: '10px', borderRadius: '6px', backgroundColor: '#f8fafc', border: '1px solid #e2e8f0' }}>
                <MapPin size={14} style={{ color: '#94a3b8', marginTop: '2px', flexShrink: 0 }} />
                <span style={{ color: '#1e293b', fontSize: '0.875rem', lineHeight: 1.4 }}>{row.surveyAddress || '—'}</span>
              </div>
            </Field>
            <Field label="Coordinates">
              {row.surveyLat && row.surveyLng ? (
                <div style={{ display: 'flex', gap: '10px', alignItems: 'center', flexWrap: 'wrap' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
                    <MapPin size={14} style={{ color: '#94a3b8' }} />
                    <span style={{ fontWeight: 500, color: '#1e293b', fontSize: '0.875rem', borderBottom: '1px dotted #cbd5e1' }}>
                      {[row.neighbourhood, row.city].filter(Boolean).join(', ') || 'Pinned location'}
                    </span>
                  </div>
                  <a
                    href={`https://www.google.com/maps?q=${row.surveyLat},${row.surveyLng}`}
                    target="_blank" rel="noopener noreferrer"
                    style={{
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: '4px',
                      padding: '4px 10px',
                      fontSize: '0.75rem',
                      fontWeight: 600,
                      borderRadius: '20px',
                      color: '#0A1317',
                      border: '1px solid rgba(10, 19, 23, 0.1)',
                      backgroundColor: 'rgba(10, 19, 23, 0.05)',
                      textDecoration: 'none'
                    }}
                  >
                    <Map size={12} />
                    View on map
                  </a>
                </div>
              ) : <span style={{ color: '#94a3b8' }}>—</span>}
            </Field>
          </SectionCard>
        </div>

        <div style={{ marginTop: '20px' }}>
          <SectionCard icon={Info} title="Contact & Compliance" accent="primary">
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px' }}>
              <ReadField label="Phone" value={row.phone} />
              <Field label="Data Consent"><Pill label={row.dataConsent && titleCase(row.dataConsent)} color={consentTone(row.dataConsent)} /></Field>
              <ReadField label="Last Updated" value={row.lastUpdated} />
            </div>
            {row.notes && (
              <div style={{ padding: '12px', borderRadius: '6px', backgroundColor: '#fffbeb', border: '1px solid #fef3c7', marginTop: '12px' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '4px' }}>
                  <StickyNote size={14} style={{ color: '#d97706' }} />
                  <span style={{ color: '#d97706', textTransform: 'uppercase', letterSpacing: '0.05em', fontSize: '0.68rem', fontWeight: 700 }}>Notes</span>
                </div>
                <span style={{ color: '#1e293b', fontSize: '0.875rem' }}>{row.notes}</span>
              </div>
            )}
          </SectionCard>
        </div>
      </div>
    </div>
  );
}

function ClientRow({ row, onEdit, onDelete }) {
  const [open, setOpen] = useState(false);

  return (
    <Fragment>
      <TableRow
        onClick={() => setOpen((o) => !o)}
        style={{
          cursor: 'pointer',
          backgroundColor: open ? 'rgba(10, 19, 23, 0.02)' : undefined
        }}
      >
        <TableCell>
          <button
            onClick={(e) => { e.stopPropagation(); setOpen((o) => !o); }}
            style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#64748b', display: 'flex', alignItems: 'center' }}
          >
            {open ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
          </button>
        </TableCell>
        <TableCell style={{ whiteSpace: 'nowrap' }}>
          <span style={{ fontFamily: 'monospace', fontWeight: 700, color: '#0A1317', backgroundColor: 'rgba(10, 19, 23, 0.08)', padding: '2px 8px', borderRadius: '4px', border: '1px solid rgba(10, 19, 23, 0.1)', fontSize: '0.75rem' }}>
            {row.logicalId}
          </span>
        </TableCell>
        <TableCell>
          <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
            <UserAvatar name={row.name} size={38} />
            <div style={{ minWidth: 0 }}>
              <div style={{ fontWeight: 600, color: '#0f172a', fontSize: '0.875rem' }}>{row.name}</div>
              <div style={{ marginTop: '2px' }}>
                {row.businessType && (
                  <span style={{ fontSize: '0.68rem', fontWeight: 600, backgroundColor: '#f1f5f9', color: '#475569', padding: '2px 6px', borderRadius: '4px' }}>
                    {titleCase(row.businessType)}
                  </span>
                )}
              </div>
            </div>
          </div>
        </TableCell>
        <TableCell>
          <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
            <Phone size={14} style={{ color: '#94a3b8' }} />
            <div>
              <div style={{ fontSize: '0.875rem', color: '#0f172a' }}>{row.phone || '—'}</div>
              {row.frequency && <div style={{ fontSize: '0.75rem', color: '#64748b' }}>{row.frequency}</div>}
            </div>
          </div>
        </TableCell>
        <TableCell>
          <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
            <MapPin size={14} style={{ color: '#94a3b8' }} />
            <div>
              <div style={{ fontSize: '0.875rem', color: '#0f172a' }}>{row.city || '—'}{row.businessState ? `, ${row.businessState}` : ''}</div>
              {row.neighbourhood && <div style={{ fontSize: '0.75rem', color: '#64748b' }}>{row.neighbourhood}</div>}
            </div>
          </div>
        </TableCell>
        <TableCell>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '12px' }}>
            <Metric label="Parcels" value={Number(row.parcelVolume).toLocaleString()} />
            <div style={{ width: '1px', height: '24px', backgroundColor: '#e2e8f0' }} />
            <Metric label="Contracts" value={row.activeContracts} color="#0A1317" />
          </div>
        </TableCell>
        <TableCell>
          <StatusChip status={row.status} />
        </TableCell>
        <TableCell style={{ textAlign: 'right' }} onClick={(e) => e.stopPropagation()}>
          <div style={{ display: 'inline-flex', gap: '8px' }}>
            <button
              onClick={() => onEdit(row)}
              style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '6px', borderRadius: '4px', color: '#475569' }}
              className="action-btn"
              title="Edit"
            >
              <Edit size={16} />
            </button>
            <button
              onClick={() => onDelete(row)}
              style={{ background: 'none', border: 'none', cursor: 'pointer', padding: '6px', borderRadius: '4px', color: '#dc2626' }}
              className="action-btn"
              title="Delete"
            >
              <Trash2 size={16} />
            </button>
          </div>
        </TableCell>
      </TableRow>
      {open && (
        <TableRow>
          <TableCell colSpan={8} style={{ padding: 0, backgroundColor: '#f8fafc' }}>
            <ClientDetail row={row} onEdit={onEdit} />
          </TableCell>
        </TableRow>
      )}
    </Fragment>
  );
}

export default function Tenants() {
  const [selectedDate, setSelectedDate] = useState(() => dayjs().format('YYYY-MM-DD'));
  const [clients, setClients] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const [searchParams] = useSearchParams();
  const [tab, setTab] = useState(0);
  const [search, setSearch] = useState(searchParams.get('q') || '');
  const [page, setPage] = useState(0);
  const [rpp, setRpp] = useState(10);

  useEffect(() => {
    const q = searchParams.get('q');
    if (q != null) { setSearch(q); setPage(0); }
  }, [searchParams]);

  const [dialog, setDialog] = useState({ open: false, mode: 'add', initial: null });
  const [toDelete, setToDelete] = useState(null);
  const [deleting, setDeleting] = useState(false);

  const load = (silent = false) => {
    if (!silent) {
      setLoading(true);
      setError(null);
    }
    fetchClients()
      .then((points) => setClients(points.map(toClient)))
      .catch((e) => {
        if (!silent) setError(e.message || 'Failed to load clients');
      })
      .finally(() => {
        if (!silent) setLoading(false);
      });
  };

  useEffect(() => { 
    load(); 
    const intervalId = setInterval(() => {
      load(true);
    }, 10000);
    return () => clearInterval(intervalId);
  }, []);

  const stats = useMemo(() => ({
    total: clients.length,
    newCount: clients.filter((c) => c.status === 'newClient').length,
    parcels: clients.reduce((s, c) => s + (Number(c.parcelVolume) || 0), 0),
    contracts: clients.reduce((s, c) => s + (Number(c.activeContracts) || 0), 0)
  }), [clients]);

  const tabs = useMemo(() => {
    const seen = [];
    clients.forEach((c) => { if (!seen.includes(c.status)) seen.push(c.status); });
    return [{ key: 'all', label: 'All' }, ...seen.map((s) => ({ key: s, label: titleCase(s) }))];
  }, [clients]);

  const tabKey = tabs[Math.min(tab, tabs.length - 1)]?.key || 'all';

  const counts = useMemo(() => {
    const c = { all: clients.length };
    clients.forEach((cl) => { c[cl.status] = (c[cl.status] || 0) + 1; });
    return c;
  }, [clients]);

  const filtered = useMemo(
    () =>
      clients.filter((t) => {
        const matchTab = tabKey === 'all' || t.status === tabKey;
        const matchSearch =
          !search ||
          [t.name, t.phone, t.city, t.businessType, t.clientId, t.neighbourhood]
            .join(' ').toLowerCase().includes(search.toLowerCase());
        return matchTab && matchSearch;
      }),
    [clients, tabKey, search]
  );

  const paged = filtered.slice(page * rpp, page * rpp + rpp);

  const handleSaved = () => { setDialog({ open: false, mode: 'add', initial: null }); load(); };

  const confirmDelete = async () => {
    setDeleting(true);
    try {
      await deleteClient(toDelete.id);
      setToDelete(null);
      load();
    } catch (e) {
      setError(e.message || 'Failed to delete client');
    } finally {
      setDeleting(false);
    }
  };

  return (
    <div style={{ fontFamily: 'system-ui, sans-serif' }}>
      <PageHeader
        title="Clients"
        action={
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px', flexWrap: 'nowrap' }}>
            <div style={{ flex: '0 1 320px', minWidth: '200px' }}>
              <TextInput
                label="Search clients"
                isLabelHidden
                placeholder="Search clients…"
                startIcon={<Search size={16} />}
                hasClear
                value={search}
                onChange={(v) => { setSearch(v); setPage(0); }}
              />
            </div>
            <input
              type="date"
              className="clients-date-picker"
              value={selectedDate}
              onChange={(e) => setSelectedDate(e.target.value)}
              style={{
                padding: '8px 12px',
                borderRadius: '10px',
                border: '1px solid rgba(5, 54, 89, 0.12)',
                fontSize: '0.875rem',
                fontWeight: 500,
                fontFamily: 'inherit',
                color: '#1e293b',
                backgroundColor: '#ffffff',
                outline: 'none',
                cursor: 'pointer',
                transition: 'all 0.2s ease',
                boxShadow: '0 1px 2px rgba(15, 23, 42, 0.04)',
                flexShrink: 0,
                width: '150px'
              }}
              onFocus={(e) => {
                e.target.style.borderColor = '#0A1317';
                e.target.style.boxShadow = '0 0 0 3px rgba(10, 19, 23, 0.12)';
              }}
              onBlur={(e) => {
                e.target.style.borderColor = 'rgba(5, 54, 89, 0.12)';
                e.target.style.boxShadow = '0 1px 2px rgba(15, 23, 42, 0.04)';
              }}
            />
            <Button
              variant="primary"
              icon={<Plus size={14} />}
              onClick={() => setDialog({ open: true, mode: 'add', initial: null })}
              label="Add Client"
              style={{ flexShrink: 0 }}
            />
          </div>
        }
      />

      {/* Stats row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '16px', marginBottom: '24px' }}>
        <StatCard size="sm" title="Total Clients" value={stats.total} icon={Building2} />
        <StatCard size="sm" title="New Clients" value={stats.newCount} icon={UserPlus} color="primary" />
        <StatCard size="sm" title="Total Parcel Volume" value={stats.parcels.toLocaleString()} icon={Package} color="primary" />
        <StatCard size="sm" title="Active Contracts" value={stats.contracts} icon={Handshake} color="primary" />
      </div>

      <Card style={{ 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)' }}>

        {/* Tabs */}
        <div style={{ display: 'flex', padding: '0 24px', borderBottom: '1px solid rgba(5, 54, 89, 0.06)', overflowX: 'auto', gap: '24px' }}>
          {tabs.map((t, i) => (
            <div
              key={t.key}
              onClick={() => { setTab(i); setPage(0); }}
              style={{
                padding: '16px 0',
                cursor: 'pointer',
                borderBottom: tab === i ? '2px solid #0A1317' : '2px solid transparent',
                color: tab === i ? '#0A1317' : '#64748b',
                fontWeight: tab === i ? 600 : 500,
                fontSize: '0.875rem',
                transition: 'all 0.2s'
              }}
            >
              <TabLabelCount label={t.label} count={counts[t.key] || 0} active={tab === i} />
            </div>
          ))}
        </div>

        {error && (
          <div style={{ padding: '16px', backgroundColor: '#fef2f2', border: '1px solid #fca5a5', borderRadius: '8px', color: '#b91c1c', margin: '20px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span>{error}</span>
            <Button label="Retry" variant="ghost" size="sm" onClick={() => load(false)} />
          </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>
        ) : paged.length === 0 ? (
          <EmptyState title="No clients found" caption="Try a different tab or search term, or add a client." />
        ) : (
          <Table density="balanced" dividers="rows" hasHover>
            <TableHeader>
              <TableRow isHeaderRow>
                <TableHeaderCell style={{ width: '48px' }} />
                <TableHeaderCell>ID</TableHeaderCell>
                <TableHeaderCell>Client</TableHeaderCell>
                <TableHeaderCell>Contact</TableHeaderCell>
                <TableHeaderCell>Location</TableHeaderCell>
                <TableHeaderCell style={{ textAlign: 'center' }}>Volume</TableHeaderCell>
                <TableHeaderCell>Status</TableHeaderCell>
                <TableHeaderCell style={{ textAlign: 'right' }}>Actions</TableHeaderCell>
              </TableRow>
            </TableHeader>
            <TableBody>
              {paged.map((row) => (
                <ClientRow
                  key={row.id}
                  row={row}
                  onEdit={(r) => setDialog({ open: true, mode: 'edit', initial: r })}
                  onDelete={(r) => setToDelete(r)}
                />
              ))}
            </TableBody>
          </Table>
        )}

        <TablePagination page={page} rpp={rpp} total={filtered.length} onPageChange={setPage} onRppChange={setRpp} />
      </Card>

      <ClientFormDialog
        open={dialog.open}
        mode={dialog.mode}
        initial={dialog.initial}
        onClose={() => setDialog({ open: false, mode: 'add', initial: null })}
        onSaved={handleSaved}
      />

      <AlertDialog
        isOpen={!!toDelete}
        onOpenChange={(o) => { if (!o) setToDelete(null); }}
        title="Delete client?"
        description={toDelete ? `This will permanently remove ${toDelete.name} from the doormile_clients collection. This cannot be undone.` : ''}
        actionLabel="Delete"
        onAction={confirmDelete}
        isActionLoading={deleting}
      />

      <style>{`
        .action-btn:hover {
          background-color: #f1f5f9;
        }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
      `}</style>
    </div>
  );
}
