import { CodeBlock } from '@cameleer/design-system';
import type { ProcessorNode, ExecutionDetail } from '../types';
import styles from '../ExecutionDiagram.module.css';

interface ErrorTabProps {
  processor: ProcessorNode | null;
  executionDetail: ExecutionDetail;
}

function extractExceptionType(errorMessage: string): string {
  const colonIdx = errorMessage.indexOf(':');
  if (colonIdx > 0) {
    return errorMessage.substring(0, colonIdx).trim();
  }
  return 'Error';
}

export function ErrorTab({ processor, executionDetail }: ErrorTabProps) {
  const errorMessage = processor?.errorMessage || executionDetail.errorMessage;
  const errorStackTrace = processor?.errorStackTrace || executionDetail.errorStackTrace;

  if (!errorMessage) {
    return (
      <div className={styles.emptyState}>
        {processor
          ? 'No error on this processor'
          : 'No error on this exchange'}
      </div>
    );
  }

  const exceptionType = extractExceptionType(errorMessage);

  return (
    <div>
      <div className={styles.errorType}>{exceptionType}</div>
      <div className={styles.errorMessage}>{errorMessage}</div>
      {errorStackTrace && (
        <>
          <div className={styles.errorStackLabel}>Stack Trace</div>
          <div className={styles.errorStackWrap}>
            <CodeBlock content={errorStackTrace} copyable />
          </div>
        </>
      )}
    </div>
  );
}
