import { useEffect, useMemo } from "react";
import { Loader2 } from "lucide-react";
import { trpc } from "@/lib/trpc";
import {
  groupPhasesByDependencyLevel,
  type DependencyEdge,
} from "@codewalk-district/shared";
import {
  ExecutionProvider,
  useExecutionContext,
  TaskModal,
  PlanSection,
  type PhaseData,
  type FlatTaskEntry,
} from "@/components/execution";
import type { SerializedTask } from "@/components/TaskRow";
import { PipelineGraph } from "./PipelineGraph";

interface PipelineTabProps {
  initiativeId: string;
  phases: PhaseData[];
  phasesLoading: boolean;
}

export function PipelineTab({ initiativeId, phases, phasesLoading }: PipelineTabProps) {
  return (
    <ExecutionProvider>
      <PipelineTabInner
        initiativeId={initiativeId}
        phases={phases}
        phasesLoading={phasesLoading}
      />
      <TaskModal />
    </ExecutionProvider>
  );
}

function PipelineTabInner({ initiativeId, phases, phasesLoading }: PipelineTabProps) {
  const { handleRegisterTasks, handleTaskCounts } = useExecutionContext();

  // Fetch all tasks for the initiative
  const tasksQuery = trpc.listInitiativeTasks.useQuery(
    { initiativeId },
    { enabled: phases.length > 0 },
  );
  const allTasks = (tasksQuery.data ?? []) as SerializedTask[];

  // Fetch dependency edges
  const depsQuery = trpc.listInitiativePhaseDependencies.useQuery(
    { initiativeId },
    { enabled: phases.length > 0 },
  );
  const dependencyEdges: DependencyEdge[] = depsQuery.data ?? [];

  // Group tasks by phaseId
  const tasksByPhase = useMemo(() => {
    const map: Record<string, SerializedTask[]> = {};
    for (const task of allTasks) {
      if (task.phaseId) {
        if (!map[task.phaseId]) map[task.phaseId] = [];
        map[task.phaseId].push(task);
      }
    }
    return map;
  }, [allTasks]);

  // Compute pipeline columns
  const columns = useMemo(
    () => groupPhasesByDependencyLevel(phases, dependencyEdges),
    [phases, dependencyEdges],
  );

  // Register tasks with ExecutionContext for TaskModal
  useEffect(() => {
    for (const phase of phases) {
      const phaseTasks = tasksByPhase[phase.id] ?? [];
      const entries: FlatTaskEntry[] = phaseTasks.map((task) => ({
        task,
        phaseName: phase.name,
        agentName: null,
        blockedBy: [],
        dependents: [],
      }));
      handleRegisterTasks(phase.id, entries);
      handleTaskCounts(phase.id, {
        complete: phaseTasks.filter((t) => t.status === "completed").length,
        total: phaseTasks.length,
      });
    }
  }, [phases, tasksByPhase, handleRegisterTasks, handleTaskCounts]);

  // Empty state
  if (!phasesLoading && phases.length === 0) {
    return (
      <PlanSection
        initiativeId={initiativeId}
        phasesLoaded={!phasesLoading}
        phases={phases}
      />
    );
  }

  // Loading
  if (phasesLoading || tasksQuery.isLoading) {
    return (
      <div className="flex items-center justify-center py-12 text-muted-foreground">
        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
        Loading pipeline...
      </div>
    );
  }

  return <PipelineGraph columns={columns} tasksByPhase={tasksByPhase} />;
}
