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

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

type StatusVariant = '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 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;

  if (!showChain) return null;

  return (
    <div className={styles.header}>
      {showChain && (
        <div className={styles.chain}>
          <span className={styles.chainLabel}>Correlated Exchanges</span>
          {chain.map((ce: any) => {
            const isCurrent = ce.executionId === detail.executionId;
            const variant = statusVariant(ce.status);
            const statusCls =
              variant === 'success' ? styles.chainNodeSuccess
              : variant === 'error' ? styles.chainNodeError
              : variant === 'running' ? styles.chainNodeRunning
              : styles.chainNodeWarning;
            return (
              <button
                key={ce.executionId}
                className={`${styles.chainNode} ${statusCls} ${isCurrent ? styles.chainNodeCurrent : ''}`}
                onClick={() => { if (!isCurrent) onExchangeClick?.(ce.executionId); }}
                title={`${ce.executionId} \u2014 ${ce.routeId}`}
              >
                <StatusDot variant={variant} />
                <span>{ce.routeId}</span>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}
