import { Badge, Tooltip, Typography } from 'antd';
import { ApiError } from '../../lib/api-client';
import { useApiPing } from '../../lib/queries/ping';
import { brandTokens } from '../../lib/theme';

const { Text } = Typography;

// Pill discreto de "fundação viva" — prova que API↔Web↔contrato Zod funcionam.
// Conscientemente mantido na Topbar enquanto o produto está em foundation;
// quando virar normal, vira indicador só em /health (Sandra/Daniel).
export function FoundationStatus() {
  const { data, error, isPending, isFetching } = useApiPing();

  if (isPending) {
    return (
      <Pill color={brandTokens.textMuted} label="API…" tooltip="Verificando conexão com a API" />
    );
  }

  if (error) {
    const detail =
      error instanceof ApiError
        ? `${error.problem.title}${error.problem.detail ? ` — ${error.problem.detail}` : ''}`
        : error.message;
    return (
      <Pill
        color={brandTokens.red}
        label="API offline"
        tooltip={
          <TooltipLines
            lines={[
              ['Erro', detail],
              ['Status', String((error as ApiError).status ?? '—')],
              ['Request', (error as ApiError).problem?.requestId ?? '—'],
            ]}
          />
        }
      />
    );
  }

  return (
    <Pill
      color={brandTokens.green}
      label={`API v${data.version}`}
      pulse={isFetching}
      tooltip={
        <TooltipLines
          lines={[
            ['Service', data.service],
            ['Version', data.version],
            ['Empresa', String(data.idEmpresa)],
            ['Request', data.requestId.slice(0, 8) + '…'],
            ['Uptime', `${data.uptimeSeconds}s`],
          ]}
        />
      }
    />
  );
}

function Pill({
  color,
  label,
  tooltip,
  pulse,
}: {
  color: string;
  label: string;
  tooltip: React.ReactNode;
  pulse?: boolean;
}) {
  return (
    <Tooltip title={tooltip} placement="bottomRight">
      <span
        style={{
          display: 'inline-flex',
          alignItems: 'center',
          gap: 8,
          height: 28,
          padding: '0 12px',
          borderRadius: 999,
          background: 'var(--bg-surface-alt)',
          border: '1px solid var(--border-subtle)',
          fontSize: 'var(--text-xs)',
          fontWeight: 'var(--font-weight-medium)',
          color: 'var(--text-muted)',
          cursor: 'default',
        }}
        aria-label={`Estado da API: ${label}`}
      >
        <Badge color={color} status={pulse ? 'processing' : undefined} />
        <span className="tabular-nums">{label}</span>
      </span>
    </Tooltip>
  );
}

function TooltipLines({ lines }: { lines: ReadonlyArray<readonly [string, string]> }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: '2px 12px' }}>
      {lines.map(([label, value]) => (
        <FragmentRow key={label} label={label} value={value} />
      ))}
    </div>
  );
}

function FragmentRow({ label, value }: { label: string; value: string }) {
  return (
    <>
      <Text style={{ color: 'rgba(255,255,255,0.65)', fontSize: 12 }}>{label}</Text>
      <Text style={{ color: '#fff', fontSize: 12 }} className="tabular-nums">
        {value}
      </Text>
    </>
  );
}
