import { useProcessorSnapshotById } from '../../../api/queries/executions';
import styles from '../ExecutionDiagram.module.css';

interface HeadersTabProps {
  executionId: string;
  processorId: string | null;
  exchangeInputHeaders?: string;
  exchangeOutputHeaders?: string;
}

function parseHeaders(json: string | undefined): Record<string, string> {
  if (!json) return {};
  try {
    return JSON.parse(json);
  } catch {
    return {};
  }
}

function HeaderTable({ headers }: { headers: Record<string, string> }) {
  const entries = Object.entries(headers).sort(([a], [b]) => a.localeCompare(b));
  if (entries.length === 0) {
    return <div className={styles.emptyState}>No headers</div>;
  }
  return (
    <table className={styles.headersTable}>
      <tbody>
        {entries.map(([k, v]) => (
          <tr key={k}>
            <td className={styles.headerKey}>{k}</td>
            <td className={styles.headerVal}>{v}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

export function HeadersTab({
  executionId,
  processorId,
  exchangeInputHeaders,
  exchangeOutputHeaders,
}: HeadersTabProps) {
  const snapshotQuery = useProcessorSnapshotById(
    processorId ? executionId : null,
    processorId,
  );

  let inputHeaders: Record<string, string>;
  let outputHeaders: Record<string, string>;

  if (processorId && snapshotQuery.data) {
    inputHeaders = parseHeaders(snapshotQuery.data.inputHeaders);
    outputHeaders = parseHeaders(snapshotQuery.data.outputHeaders);
  } else if (!processorId) {
    inputHeaders = parseHeaders(exchangeInputHeaders);
    outputHeaders = parseHeaders(exchangeOutputHeaders);
  } else {
    inputHeaders = {};
    outputHeaders = {};
  }

  if (processorId && snapshotQuery.isLoading) {
    return <div className={styles.emptyState}>Loading headers...</div>;
  }

  return (
    <div className={styles.headersSplit}>
      <div className={styles.headersColumn}>
        <div className={styles.headersColumnLabel}>Input Headers</div>
        <HeaderTable headers={inputHeaders} />
      </div>
      <div className={styles.headersColumn}>
        <div className={styles.headersColumnLabel}>Output Headers</div>
        <HeaderTable headers={outputHeaders} />
      </div>
    </div>
  );
}
