import { Skeleton } from "@/components/Skeleton";
import { useExecutionContext, type PhaseData } from "./ExecutionContext";
import { PhaseWithTasks } from "./PhaseWithTasks";
import { PlanSection } from "./PlanSection";

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

export function PhasesList({
  initiativeId,
  phases,
  phasesLoading,
  phasesLoaded,
}: PhasesListProps) {
  const { setSelectedTaskId, handleTaskCounts, handleRegisterTasks } =
    useExecutionContext();

  const firstIncompletePhaseIndex = phases.findIndex(
    (p) => p.status !== "completed",
  );

  if (phasesLoading) {
    return (
      <div className="space-y-1 pt-3">
        {Array.from({ length: 3 }).map((_, i) => (
          <Skeleton key={i} className="h-10 w-full" />
        ))}
      </div>
    );
  }

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

  return (
    <>
      {phasesLoaded &&
        phases.map((phase, idx) => {
          const serializedPhase = {
            id: phase.id,
            initiativeId: phase.initiativeId,
            name: phase.name,
            content: phase.content,
            status: phase.status,
            createdAt: String(phase.createdAt),
            updatedAt: String(phase.updatedAt),
          };

          return (
            <PhaseWithTasks
              key={phase.id}
              phase={serializedPhase}
              defaultExpanded={idx === firstIncompletePhaseIndex}
              onTaskClick={setSelectedTaskId}
              onTaskCounts={handleTaskCounts}
              registerTasks={handleRegisterTasks}
            />
          );
        })}
    </>
  );
}