import { StatusDot, MonoText, Badge } from '@cameleer/design-system';
import { useCorrelationChain } from '../../api/queries/correlation';
import type { ExecutionDetail } from '../../components/ExecutionDiagram/types';

interface ExchangeHeaderProps {
  detail: ExecutionDetail;
  onExchangeClick?: (executionId: string) => void;
}

type StatusVariant = 'success' | 'error' | 'running' | 'warning';
type BadgeColor = 'success' | 'error' | 'running' | 'warning';

function statusVariant(s: string): StatusVariant {
  switch (s) {
    case 'COMPLETED': return 'success';
    case 'FAILED': return 'error';
    case 'RUNNING': return 'running';
    default: return 'warning';
  }
}

function badgeColor(s: string): BadgeColor {
  switch (s) {
    case 'COMPLETED': return 'success';
    case 'FAILED': return 'error';
    case 'RUNNING': return 'running';
    default: return 'warning';
  }
}

function formatDuration(ms: number): string {
  if (ms >= 60_000) return `${(ms / 1000).toFixed(0)}s`;
  if (ms >= 1000) return `${(ms / 1000).toFixed(2)}s`;
  return `${ms}ms`;
}

export function ExchangeHeader({ detail, onExchangeClick }: ExchangeHeaderProps) {
  const { data: chainResult } = useCorrelationChain(detail.correlationId ?? null);
  const chain = chainResult?.data;
  const showChain = chain && chain.length > 1;

  return (
    <div style={{
      display: 'flex', flexDirection: 'column', gap: '0.5rem',
      padding: '0.75rem', borderBottom: '1px solid var(--border)',
      background: 'var(--surface)', fontSize: '0.8125rem',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', flexWrap: 'wrap' }}>
        <StatusDot variant={statusVariant(detail.status)} />
        <MonoText size="xs">{detail.exchangeId || detail.executionId}</MonoText>
        <Badge label={detail.status === 'COMPLETED' ? 'OK' : detail.status} color={badgeColor(detail.status)} />
        <span style={{ color: 'var(--text-muted)' }}>{detail.routeId}</span>
        <span style={{ marginLeft: 'auto', fontFamily: 'var(--font-mono)', fontSize: '0.75rem' }}>
          {formatDuration(detail.durationMs)}
        </span>
      </div>

      {showChain && (
        <div style={{ display: 'flex', gap: '0.25rem', flexWrap: 'wrap', alignItems: 'center' }}>
          <span style={{ fontSize: '0.6875rem', color: 'var(--text-muted)', marginRight: '0.25rem' }}>
            Correlated:
          </span>
          {chain.map((e) => (
            <button
              key={e.executionId}
              onClick={() => onExchangeClick?.(e.executionId)}
              style={{
                background: e.executionId === detail.executionId ? 'var(--surface-active)' : 'var(--surface)',
                border: '1px solid var(--border)',
                borderRadius: '4px',
                padding: '0.125rem 0.375rem',
                cursor: 'pointer',
                fontSize: '0.6875rem',
                fontFamily: 'var(--font-mono)',
                color: e.status === 'FAILED' ? 'var(--error)' : 'var(--text-secondary)',
              }}
            >
              {e.executionId.slice(0, 8)}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
