import type { ProviderHealthDto } from '@navi/types';
import { formatDate } from '@navi/ui';
import { AccessDenied } from '../../../components/AccessDenied';
import { EmptyState, Notice, PageHeader, StatusBadge } from '../../../components/DashboardPrimitives';
import { dashboardApi } from '../../../lib/api';
import { requireDashboardRoute } from '../../../lib/permissions';

export default async function ProviderHealth() {
  const gate = await requireDashboardRoute('/provider-health');
  if (!gate.allowed) return <AccessDenied required={gate.required} />;

  const health = (await dashboardApi<ProviderHealthDto[]>('/provider-control/provider-health')) ?? [];

  return (
    <div className="stack">
      <PageHeader title="Provider health" eyebrow="Control Tower" />
      <Notice tone="info" title="Safe mock health foundation" body="Wave 1 health checks are intentionally safe and do not call external providers yet. Real network checks can be added per provider after credentials and contracts are approved." />
      <Notice tone="info" title="Support-safe view" body="This page is read-only and can be exposed to Support only through provider health permissions. Global provider settings remain hidden from partner users." />
      <div className="card">
        {health.length ? (
          <div className="table-wrap">
            <table className="table">
              <thead><tr><th>Provider</th><th>Environment</th><th>Enabled</th><th>Health</th><th>Readiness</th><th>Last check</th><th>Last sync</th><th>Error</th></tr></thead>
              <tbody>
                {health.map((provider) => (
                  <tr key={provider.id}>
                    <td><strong>{provider.name}</strong><div className="muted">{provider.categoryKind}</div></td>
                    <td><StatusBadge value={provider.environment} /></td>
                    <td><StatusBadge value={provider.enabled ? 'ENABLED' : 'DISABLED'} /></td>
                    <td><StatusBadge value={provider.healthStatus} /></td>
                    <td>
                      <div className="button-row">
                        {provider.safetyWarnings.slice(0, 3).map((warning) => (
                          <StatusBadge key={warning.code} value={`${warning.level}_${warning.label}`.toUpperCase().replace(/\s/g, '_')} />
                        ))}
                      </div>
                    </td>
                    <td>{provider.lastHealthCheckAt ? formatDate(provider.lastHealthCheckAt) : 'Not checked'}</td>
                    <td>{provider.lastSyncAt ? formatDate(provider.lastSyncAt) : 'No sync yet'}</td>
                    <td>{provider.errorMessage ?? <span className="muted">No error</span>}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <EmptyState title="No provider health records" body="Provider integrations will appear here after they are configured." />
        )}
      </div>
    </div>
  );
}
