'use client';

import { useState } from 'react';
import { Loader2, CheckCircle2, XCircle } from 'lucide-react';
import { toast } from 'sonner';

import { Button } from '@/components/ui/button';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';

interface TestResponse {
  ok: boolean;
  visitors?: number;
  error?: string;
}

/**
 * Hits POST /api/v1/admin/umami/test which calls Umami's `/api/websites/:id/
 * active` to verify auth + websiteId in one request. On success, shows the
 * live visitor count as proof we got real data back.
 */
export function UmamiTestButton() {
  const [pending, setPending] = useState(false);
  const [result, setResult] = useState<TestResponse | null>(null);

  async function runTest() {
    setPending(true);
    setResult(null);
    try {
      const res = await apiFetch<{ data: TestResponse }>('/api/v1/admin/umami/test', {
        method: 'POST',
      });
      setResult(res.data);
      if (res.data.ok) {
        toast.success(`Umami reachable - ${res.data.visitors ?? 0} active visitor(s) right now`);
      } else {
        toast.error(res.data.error ?? 'Umami test failed');
      }
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Test failed';
      setResult({ ok: false, error: message });
      toastError(err);
    } finally {
      setPending(false);
    }
  }

  return (
    <div className="flex items-center gap-3">
      {result &&
        (result.ok ? (
          <span className="flex items-center text-xs text-green-600">
            <CheckCircle2 className="mr-1 h-3.5 w-3.5" aria-hidden />
            Connected ({result.visitors ?? 0} active)
          </span>
        ) : (
          <span className="flex items-center text-xs text-destructive">
            <XCircle className="mr-1 h-3.5 w-3.5" aria-hidden />
            {result.error ?? 'Failed'}
          </span>
        ))}
      <Button type="button" size="sm" variant="outline" onClick={runTest} disabled={pending}>
        {pending ? <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" aria-hidden /> : null}
        Test connection
      </Button>
    </div>
  );
}
