import { useCallback, useMemo, useState } from "react";
import { Loader2, Plus, Sparkles } from "lucide-react";
import { Button } from "@/components/ui/button";
import { trpc } from "@/lib/trpc";

interface PhaseActionsProps {
  initiativeId: string;
  phases: Array<{ id: string; status: string }>;
  onAddPhase: () => void;
  phasesWithoutTasks: string[];
  detailAgentByPhase: Map<string, { id: string; status: string }>;
}

export function PhaseActions({
  onAddPhase,
  phasesWithoutTasks,
  detailAgentByPhase,
}: PhaseActionsProps) {
  const detailMutation = trpc.spawnArchitectDetail.useMutation();
  const [isDetailingAll, setIsDetailingAll] = useState(false);

  // Phases eligible for detailing: no tasks AND no active detail agent
  const eligiblePhaseIds = useMemo(
    () => phasesWithoutTasks.filter((id) => !detailAgentByPhase.has(id)),
    [phasesWithoutTasks, detailAgentByPhase],
  );

  // Count of phases currently being detailed
  const activeDetailCount = useMemo(() => {
    let count = 0;
    for (const [, agent] of detailAgentByPhase) {
      if (agent.status === "running" || agent.status === "waiting_for_input") {
        count++;
      }
    }
    return count;
  }, [detailAgentByPhase]);

  const handleDetailAll = useCallback(async () => {
    setIsDetailingAll(true);
    try {
      for (const phaseId of eligiblePhaseIds) {
        try {
          await detailMutation.mutateAsync({ phaseId });
        } catch {
          // CONFLICT errors expected if agent already exists — continue
        }
      }
    } finally {
      setIsDetailingAll(false);
    }
  }, [eligiblePhaseIds, detailMutation]);

  return (
    <div className="flex items-center gap-2">
      {activeDetailCount > 0 && (
        <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
          <Loader2 className="h-3 w-3 animate-spin" />
          Detailing ({activeDetailCount})
        </div>
      )}
      <Button
        variant="ghost"
        size="icon"
        className="h-7 w-7"
        onClick={onAddPhase}
        title="Add phase"
      >
        <Plus className="h-4 w-4" />
      </Button>
      <Button
        variant="outline"
        size="sm"
        disabled={eligiblePhaseIds.length === 0 || isDetailingAll}
        onClick={handleDetailAll}
        className="gap-1.5"
      >
        {isDetailingAll ? (
          <Loader2 className="h-3.5 w-3.5 animate-spin" />
        ) : (
          <Sparkles className="h-3.5 w-3.5" />
        )}
        Detail All
      </Button>
    </div>
  );
}
