import { useNavigate } from 'react-router';
import { Badge, Button, DataTable, EmptyState, Spinner } from '@cameleer/design-system';
import type { Column } from '@cameleer/design-system';
import { Plus, Building } from 'lucide-react';
import { useVendorTenants } from '../../api/vendor-hooks';
import { ServerStatusBadge } from '../../components/ServerStatusBadge';
import { tierColor } from '../../utils/tier';
import type { VendorTenantSummary } from '../../types/api';

function licenseDaysLabel(expiry: string | null): string {
  if (!expiry) return 'None';
  const diff = Math.ceil((new Date(expiry).getTime() - Date.now()) / 86_400_000);
  if (diff < 0) return 'Expired';
  return `${diff}d`;
}

function statusColor(status: string): 'success' | 'error' | 'warning' | 'auto' {
  switch (status?.toUpperCase()) {
    case 'ACTIVE': return 'success';
    case 'SUSPENDED': return 'warning';
    case 'PROVISIONING': return 'auto';
    case 'ERROR': return 'error';
    default: return 'auto';
  }
}

const columns: Column<VendorTenantSummary>[] = [
  {
    key: 'name',
    header: 'Name',
    render: (_v, row) => row.name,
  },
  {
    key: 'slug',
    header: 'Slug',
    render: (_v, row) => (
      <span style={{ fontFamily: 'monospace', fontSize: '0.875rem' }}>{row.slug}</span>
    ),
  },
  {
    key: 'tier',
    header: 'Tier',
    render: (_v, row) => <Badge label={row.tier} color={tierColor(row.tier)} />,
  },
  {
    key: 'status',
    header: 'Status',
    render: (_v, row) => <Badge label={row.status} color={statusColor(row.status)} />,
  },
  {
    key: 'serverState',
    header: 'Server',
    render: (_v, row) => <ServerStatusBadge state={row.serverState} />,
  },
  {
    key: 'licenseExpiry',
    header: 'License',
    render: (_v, row) => {
      const label = licenseDaysLabel(row.licenseExpiry);
      const color = label === 'Expired' ? 'error' : label === 'None' ? 'auto' : 'auto';
      return <Badge label={label} color={color} />;
    },
  },
];

export function VendorTenantsPage() {
  const navigate = useNavigate();
  const { data: tenants, isLoading } = useVendorTenants();

  return (
    <div style={{ padding: '24px', display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h1 style={{ margin: 0, fontSize: '1.25rem', fontWeight: 600 }}>Tenants</h1>
        <Button
          variant="primary"
          onClick={() => navigate('/vendor/tenants/new')}
        >
          <Plus size={16} style={{ marginRight: 6 }} />
          Create Tenant
        </Button>
      </div>

      {isLoading && (
        <div style={{ display: 'flex', justifyContent: 'center', padding: 48 }}>
          <Spinner />
        </div>
      )}

      {!isLoading && (!tenants || tenants.length === 0) && (
        <EmptyState
          icon={<Building size={32} />}
          title="No tenants yet"
          description="Create your first tenant to get started."
          action={
            <Button variant="primary" onClick={() => navigate('/vendor/tenants/new')}>
              <Plus size={16} style={{ marginRight: 6 }} />
              Create Tenant
            </Button>
          }
        />
      )}

      {!isLoading && tenants && tenants.length > 0 && (
        <DataTable
          columns={columns}
          data={tenants}
          onRowClick={(row) => navigate(`/vendor/tenants/${row.id}`)}
        />
      )}
    </div>
  );
}
