/**
 * List view for /v1/tenants/{id}/telegram/bots.
 *
 * Layout:
 *   - For super_admin: a tenant picker (dropdown) at the top so
 *     they can switch between companies.
 *   - tenant_admin is not yet supported (canManageTelegram is
 *     super_admin only in W3); we still surface a friendly
 *     empty state.
 *   - Below: search + status filter + the table.
 *
 * tenant-admin scope is enforced server-side (RequireRole
 * "super_admin" on every endpoint).
 */

import { useEffect, useMemo, useState } from 'react';
import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Search, Send } 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 { canManageTelegram, isSuperAdmin } from '@/lib/scope';
import { useTenantsList } from '@/features/companies/api';
import { useTelegramBotsList } from './api';
import { CreateTelegramBotDialog } from './create-dialog';
import {
  StatusBadge,
  TokenSetBadge,
  formatDate,
  formatDateTime,
  truncate,
} from './format';
import type { TelegramBotStatus } from './types';

const STATUS_OPTIONS = [
  { value: '', label: 'All' },
  { value: 'active', label: 'Active' },
  { value: 'paused', label: 'Paused' },
];

export function TelegramBotsList() {
  const navigate = useNavigate();
  const params = useParams();
  const { user } = useAuth();
  const canCreate = canManageTelegram(user?.role);
  const isAdmin = isSuperAdmin(user?.role);

  const tenantId = params.id;

  const [searchParams, setSearchParams] = useSearchParams();
  const [q, setQ] = useState(searchParams.get('q') ?? '');
  const status = searchParams.get('status') ?? '';

  // For super_admin without a tenant in the URL, list tenants to
  // populate the picker. We also auto-pick the first one so the
  // rest of the page can render immediately.
  const tenantsQ = useTenantsList({ limit: 200 });
  useEffect(() => {
    if (tenantId || !isAdmin) return;
    const first = tenantsQ.data && tenantsQ.data.items[0];
    if (first) navigate(`/telegram/${first.id}`, { replace: true });
  }, [tenantId, isAdmin, tenantsQ.data, navigate]);

  // Debounce q -> URL (300ms).
  useEffect(() => {
    const handle = setTimeout(() => {
      const next = new URLSearchParams(searchParams);
      if (q.trim()) next.set('q', q.trim());
      else next.delete('q');
      setSearchParams(next, { replace: true });
    }, 300);
    return () => clearTimeout(handle);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [q]);

  const queryParams = useMemo(
    () => ({
      q: searchParams.get('q') ?? undefined,
      status: status || undefined,
      limit: 100,
    }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [searchParams, status],
  );
  const { data, isPending, isError, error, refetch } = useTelegramBotsList(
    tenantId,
    queryParams,
  );

  const onTenantChange = (next: string) => {
    if (next) navigate(`/telegram/${next}`);
    else navigate('/telegram');
  };

  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">Telegram bots</h1>
          <p className="text-sm text-muted-foreground">
            Per-company Telegram bot configuration. Each bot has its own
            token, welcome message, and default source. The token is
            write-only — the server never returns it after save.
          </p>
        </div>
        <div className="flex items-center gap-2">
          {isAdmin && tenantsQ.data ? (
            <select
              className="h-9 rounded-md border border-input bg-background px-3 text-sm"
              value={tenantId ?? ''}
              onChange={(e) => onTenantChange(e.target.value)}
              aria-label="Company"
            >
              <option value="">Select a company</option>
              {tenantsQ.data.items.map((t) => (
                <option key={t.id} value={t.id}>
                  {t.display_name}
                </option>
              ))}
            </select>
          ) : null}
          {canCreate && tenantId ? <CreateTelegramBotDialog tenantId={tenantId} /> : null}
        </div>
      </div>

      {tenantId ? (
        <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 id or name"
              className="pl-8"
              value={q}
              onChange={(e) => setQ(e.target.value)}
              aria-label="Search bots"
            />
          </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(searchParams);
                    if (opt.value) next.set('status', opt.value);
                    else next.delete('status');
                    setSearchParams(next, { replace: true });
                  }}
                >
                  {opt.label}
                </Button>
              );
            })}
          </div>
        </div>
      ) : null}

      {!tenantId ? (
        <div className="rounded-md border bg-card p-8 text-center text-sm text-muted-foreground">
          {isAdmin
            ? 'Select a company above to see its telegram bots.'
            : 'Telegram bots are managed by super admins. Ask your operator to set up a bot for your company.'}
        </div>
      ) : !isAdmin ? (
        <div className="rounded-md border bg-card p-8 text-center text-sm text-muted-foreground">
          Only super admins can manage telegram bots in this version. W3 ships
          super_admin scope; per-company tenant_admin is a v1.1 follow-up.
        </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 telegram bots.</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>
      ) : 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={<Send className="h-8 w-8" />}
          title="No bots yet"
          description={
            canCreate
              ? 'Create the first telegram bot for this company.'
              : 'No telegram bots configured for this company.'
          }
          action={canCreate ? <CreateTelegramBotDialog tenantId={tenantId} /> : null}
        />
      ) : data ? (
        <>
          <div className="rounded-md border bg-card">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Name</TableHead>
                  <TableHead>ID</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Token</TableHead>
                  <TableHead>Default source</TableHead>
                  <TableHead>Welcome</TableHead>
                  <TableHead>Last rotated</TableHead>
                  <TableHead>Created</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {data.items.map((b) => (
                  <TableRow key={`${b.company_id}:${b.id}`}>
                    <TableCell>
                      <Link
                        to={`/telegram/${tenantId}/${b.id}`}
                        className="font-medium text-foreground hover:underline"
                      >
                        {b.name}
                      </Link>
                    </TableCell>
                    <TableCell>
                      <code className="rounded bg-muted px-1.5 py-0.5 text-xs">
                        {b.id}
                      </code>
                    </TableCell>
                    <TableCell>
                      <StatusBadge status={b.status as TelegramBotStatus} />
                    </TableCell>
                    <TableCell>
                      <TokenSetBadge set={b.bot_token_set} />
                    </TableCell>
                    <TableCell className="text-xs text-muted-foreground">
                      {b.default_source_id ? (
                        <code className="rounded bg-muted px-1.5 py-0.5 text-xs">
                          {b.default_source_id}
                        </code>
                      ) : (
                        '\u2014'
                      )}
                    </TableCell>
                    <TableCell className="max-w-[14rem] text-xs text-muted-foreground">
                      {truncate(b.welcome_message, 40)}
                    </TableCell>
                    <TableCell className="text-xs text-muted-foreground">
                      {formatDateTime(b.last_rotated_at)}
                    </TableCell>
                    <TableCell className="text-xs text-muted-foreground">
                      {formatDate(b.created_at)}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
          <p className="text-xs text-muted-foreground">
            Showing {data.items.length} of {data.total}
          </p>
        </>
      ) : null}
    </div>
  );
}
