/**
 * List view for /v1/tenants. Server-driven filtering (q, status)
 * with a small debounce on q to avoid hammering the backend.
 *
 * tenant_admin sees their own tenant only; the API handles the
 * scope so this view is identical for both roles.
 */

import { useEffect, useMemo, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
import { Search, Building2 } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { EmptyState } from '@/components/ui/empty-state';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';

import { useAuth } from '@/lib/auth-context';
import { canManageCompanies } from "@/lib/scope";
import { useTenantsList } from './api';
import { CreateTenantDialog } from './create-dialog';
import { StatusBadge, formatDate, formatRateLimit } from './format';

const STATUS_OPTIONS: { value: string; label: string }[] = [
  { value: '', label: 'All' },
  { value: 'active', label: 'Active' },
  { value: 'suspended', label: 'Suspended' },
  { value: 'archived', label: 'Archived' },
];

export function CompaniesList() {
  const [params, setParams] = useSearchParams();
  const [q, setQ] = useState(params.get('q') ?? '');
  const status = params.get('status') ?? '';
  const { user } = useAuth();
  const canCreate = canManageCompanies(user?.role);

  // Debounce q → URL (300ms). Keeps the API call rate sane while
  // the user is still typing.
  useEffect(() => {
    const handle = setTimeout(() => {
      const next = new URLSearchParams(params);
      if (q.trim()) next.set('q', q.trim());
      else next.delete('q');
      setParams(next, { replace: true });
    }, 300);
    return () => clearTimeout(handle);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [q]);

  const queryParams = useMemo(
    () => ({ q: params.get('q') ?? undefined, status: status || undefined, limit: 100 }),
    [params, status],
  );
  const { data, isPending, isError, error, refetch } = useTenantsList(queryParams);

  return (
    <div className="flex flex-col gap-4">
      <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">Companies</h1>
          <p className="text-sm text-muted-foreground">
            Manage the tenants that send events to the router.
          </p>
        </div>
        {canCreate ? <CreateTenantDialog /> : null}
      </div>

      <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
        <div className="relative flex-1 sm:max-w-sm">
          <Search className="pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Search by slug or name"
            className="pl-8"
            value={q}
            onChange={(e) => setQ(e.target.value)}
            aria-label="Search companies"
          />
        </div>
        <div className="flex gap-1">
          {STATUS_OPTIONS.map((opt) => {
            const active = status === opt.value;
            return (
              <Button
                key={opt.value}
                variant={active ? 'secondary' : 'ghost'}
                size="sm"
                onClick={() => {
                  const next = new URLSearchParams(params);
                  if (opt.value) next.set('status', opt.value);
                  else next.delete('status');
                  setParams(next, { replace: true });
                }}
              >
                {opt.label}
              </Button>
            );
          })}
        </div>
      </div>

      {isError ? (
        <div className="rounded-md border border-destructive/40 bg-destructive/5 p-4 text-sm text-destructive">
          <p className="font-medium">Failed to load companies.</p>
          <p className="mt-1 text-xs opacity-80">
            {error instanceof Error ? error.message : 'Unknown error'}
          </p>
          <Button
            variant="outline"
            size="sm"
            className="mt-2"
            onClick={() => refetch()}
          >
            Retry
          </Button>
        </div>
      ) : null}

      {isPending ? (
        <div className="rounded-md border bg-card p-8 text-center text-sm text-muted-foreground">
          Loading…
        </div>
      ) : data && data.items.length === 0 ? (
        <EmptyState
          icon={<Building2 className="h-8 w-8" />}
          title="No companies yet"
          description={
            canCreate
              ? 'Create the first company to start routing events.'
              : 'You will see your company here once it has been set up.'
          }
          action={canCreate ? <CreateTenantDialog /> : null}
        />
      ) : data ? (
        <>
          <div className="rounded-md border bg-card">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>Slug</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="text-right">Rate limit</TableHead>
                  <TableHead>FCM</TableHead>
                  <TableHead>Created</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {data.items.map((t) => (
                  <TableRow key={t.id}>
                    <TableCell>
                      <Link
                        to={`/companies/${t.id}`}
                        className="font-medium text-foreground hover:underline"
                      >
                        {t.display_name}
                      </Link>
                    </TableCell>
                    <TableCell>
                      <code className="rounded bg-muted px-1.5 py-0.5 text-xs">
                        {t.slug}
                      </code>
                    </TableCell>
                    <TableCell>
                      <StatusBadge status={t.status} />
                    </TableCell>
                    <TableCell className="text-right tabular-nums">
                      {formatRateLimit(t.rate_limit_per_sec)}
                    </TableCell>
                    <TableCell className="text-xs text-muted-foreground">
                      {t.fcm_shared ? 'shared' : 'dedicated'}
                    </TableCell>
                    <TableCell className="text-xs text-muted-foreground">
                      {formatDate(t.created_at)}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
          <p className="text-xs text-muted-foreground">
            Showing {data.items.length} of {data.total}
          </p>
        </>
      ) : null}
    </div>
  );
}
