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

interface PropertiesTabProps {
  executionId: string;
  processorId: string | null;
  exchangeInputProperties?: string;
  exchangeOutputProperties?: string;
}

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

function PropertiesTable({ properties }: { properties: Record<string, string> }) {
  const entries = Object.entries(properties).sort(([a], [b]) => a.localeCompare(b));
  if (entries.length === 0) {
    return <div className={styles.emptyState}>No properties</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 PropertiesTab({
  executionId,
  processorId,
  exchangeInputProperties,
  exchangeOutputProperties,
}: PropertiesTabProps) {
  const snapshotQuery = useProcessorSnapshotById(
    processorId ? executionId : null,
    processorId,
  );

  let inputProperties: Record<string, string>;
  let outputProperties: Record<string, string>;

  if (processorId && snapshotQuery.data) {
    inputProperties = parseProperties(snapshotQuery.data.inputProperties);
    outputProperties = parseProperties(snapshotQuery.data.outputProperties);
  } else if (!processorId) {
    inputProperties = parseProperties(exchangeInputProperties);
    outputProperties = parseProperties(exchangeOutputProperties);
  } else {
    inputProperties = {};
    outputProperties = {};
  }

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

  return (
    <div className={styles.headersSplit}>
      <div className={styles.headersColumn}>
        <div className={styles.headersColumnLabel}>Input Properties</div>
        <PropertiesTable properties={inputProperties} />
      </div>
      <div className={styles.headersColumn}>
        <div className={styles.headersColumnLabel}>Output Properties</div>
        <PropertiesTable properties={outputProperties} />
      </div>
    </div>
  );
}
