import type { ExecutionDetail, ProcessorNode } from '../types';
import styles from '../ExecutionDiagram.module.css';

interface TimelineTabProps {
  executionDetail: ExecutionDetail;
  selectedProcessorId: string | null;
  onSelectProcessor: (id: string) => void;
}

interface FlatProcessor {
  processorId: string;
  processorType: string;
  status: string;
  startTime: string;
  durationMs: number;
  depth: number;
}

function flattenProcessors(
  nodes: ProcessorNode[],
  depth: number,
  result: FlatProcessor[],
): void {
  for (const node of nodes) {
    const status = node.status?.toUpperCase();
    if (status === 'COMPLETED' || status === 'FAILED') {
      result.push({
        processorId: node.processorId,
        processorType: node.processorType,
        status,
        startTime: node.startTime,
        durationMs: node.durationMs,
        depth,
      });
    }
    if (node.children && node.children.length > 0) {
      flattenProcessors(node.children, depth + 1, result);
    }
  }
}

export function TimelineTab({
  executionDetail,
  selectedProcessorId,
  onSelectProcessor,
}: TimelineTabProps) {
  const flat: FlatProcessor[] = [];
  flattenProcessors(executionDetail.processors || [], 0, flat);

  if (flat.length === 0) {
    return <div className={styles.emptyState}>No processor timeline data available</div>;
  }

  const execStart = new Date(executionDetail.startTime).getTime();
  const totalDuration = executionDetail.durationMs || 1;

  return (
    <div className={styles.ganttContainer}>
      {flat.map((proc) => {
        const procStart = new Date(proc.startTime).getTime();
        const offsetPct = Math.max(0, ((procStart - execStart) / totalDuration) * 100);
        const widthPct = Math.max(0.5, (proc.durationMs / totalDuration) * 100);
        const isSelected = proc.processorId === selectedProcessorId;
        const fillClass = proc.status === 'FAILED'
          ? styles.ganttFillFailed
          : styles.ganttFillCompleted;

        return (
          <div
            key={proc.processorId}
            className={`${styles.ganttRow} ${isSelected ? styles.ganttSelected : ''}`}
            onClick={() => onSelectProcessor(proc.processorId)}
          >
            <div className={styles.ganttLabel} title={proc.processorType || proc.processorId}>
              {'  '.repeat(proc.depth)}{proc.processorType || proc.processorId}
            </div>
            <div className={styles.ganttBar}>
              <div
                className={`${styles.ganttFill} ${fillClass}`}
                style={{
                  left: `${offsetPct}%`,
                  width: `${Math.min(widthPct, 100 - offsetPct)}%`,
                }}
              />
            </div>
            <div className={styles.ganttDuration}>
              {proc.durationMs}ms
            </div>
          </div>
        );
      })}
    </div>
  );
}
