import { useMemo } from "react";
import type { PipelineColumn, DependencyEdge } from "@codewalk-district/shared";
import { PipelineStageColumn } from "./PipelineStageColumn";
import type { SerializedTask } from "@/components/TaskRow";
import type { DetailAgentInfo } from "./PipelinePhaseGroup";

interface PipelineGraphProps {
  columns: PipelineColumn<{
    id: string;
    name: string;
    status: string;
    createdAt: string | Date;
  }>[];
  tasksByPhase: Record<string, SerializedTask[]>;
  taskDepsByPhase: Record<string, Array<{ taskId: string; dependsOn: string[] }>>;
  dependencyEdges: DependencyEdge[];
  detailAgentByPhase?: Map<string, DetailAgentInfo>;
}

export function PipelineGraph({ columns, tasksByPhase, taskDepsByPhase, dependencyEdges, detailAgentByPhase }: PipelineGraphProps) {
  // Build a set of phase IDs whose dependencies are all completed
  const blockedPhaseIds = useMemo(() => {
    const phaseStatusMap = new Map<string, string>();
    for (const col of columns) {
      for (const phase of col.phases) {
        phaseStatusMap.set(phase.id, phase.status);
      }
    }
    const blocked = new Set<string>();
    for (const edge of dependencyEdges) {
      const depStatus = phaseStatusMap.get(edge.dependsOnPhaseId);
      if (depStatus !== "completed") {
        blocked.add(edge.phaseId);
      }
    }
    return blocked;
  }, [columns, dependencyEdges]);

  return (
    <div className="overflow-x-auto pb-4">
      <div className="flex min-w-max items-start gap-0">
        {columns.map((column, idx) => (
          <div key={column.depth} className="flex items-start">
            {/* Connector arrow between columns */}
            {idx > 0 && (
              <div className="flex items-center self-center px-1 py-4">
                <div className="h-px w-8 border-t border-dashed border-border" />
                <div className="h-0 w-0 border-y-[3px] border-l-[5px] border-y-transparent border-l-muted-foreground/60" />
              </div>
            )}
            <PipelineStageColumn
              phases={column.phases}
              tasksByPhase={tasksByPhase}
              taskDepsByPhase={taskDepsByPhase}
              blockedPhaseIds={blockedPhaseIds}
              detailAgentByPhase={detailAgentByPhase}
            />
          </div>
        ))}
      </div>
    </div>
  );
}
