import { useState } from 'react';
import {
  probeService,
  VIGTHORIA_SERVICE_CATALOG,
  type ServiceHealth,
} from '@/lib/service-catalog';

export function InfrastructureHealthPanel() {
  const [results, setResults] = useState<ServiceHealth[]>([]);
  const [running, setRunning] = useState(false);

  const probeAll = async () => {
    setRunning(true);
    setResults(await Promise.all(VIGTHORIA_SERVICE_CATALOG.map(probeService)));
    setRunning(false);
  };

  return (
    <div className="services-panel__body">
      <p className="services-panel__intro">
        Live reachability checks for the services Workbench depends on. A “protected” result is healthy connectivity with an expected authentication challenge.
      </p>
      <div className="services-panel__actions">
        <button type="button" className="is-primary" disabled={running} onClick={() => void probeAll()}>
          {running ? 'Checking infrastructure…' : 'Run health checks'}
        </button>
      </div>
      <div className="service-health">
        {VIGTHORIA_SERVICE_CATALOG.map((service) => {
          const result = results.find((candidate) => candidate.id === service.id) ?? null;
          return (
            <article key={service.id} className={`service-health__row ${result ? `is-${result.state}` : ''}`}>
              <div>
                <strong>{service.name}</strong>
                <span>{service.apiVersion} · {service.authScope}</span>
              </div>
              <div className="service-health__result">
                <strong>{result?.state ?? 'not checked'}</strong>
                <span>{result ? `${result.status ?? 'network'} · ${result.latencyMs} ms · ${result.detail}` : service.url}</span>
              </div>
            </article>
          );
        })}
      </div>
    </div>
  );
}
