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

interface PlanSectionProps {
  initiativeId: string;
  phasesLoaded: boolean;
  phases: Array<{ status: string }>;
  onAddPhase?: () => void;
}

export function PlanSection({
  initiativeId,
  phasesLoaded,
  phases,
  onAddPhase,
}: PlanSectionProps) {
  // Plan agent tracking
  const agentsQuery = trpc.listAgents.useQuery();
  const allAgents = agentsQuery.data ?? [];
  const planAgent = useMemo(() => {
    const candidates = allAgents
      .filter(
        (a) =>
          a.mode === "plan" &&
          a.initiativeId === initiativeId &&
          !a.userDismissedAt &&
          ["running", "waiting_for_input", "idle"].includes(a.status),
      )
      .sort(
        (a, b) =>
          new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
      );
    return candidates[0] ?? null;
  }, [allAgents, initiativeId]);

  const isPlanRunning = planAgent?.status === "running";

  // Query change sets when we have a completed plan agent
  const changeSetsQuery = trpc.listChangeSets.useQuery(
    { agentId: planAgent?.id ?? "" },
    { enabled: !!planAgent && planAgent.status === "idle" },
  );
  const latestChangeSet = useMemo(
    () => (changeSetsQuery.data ?? []).find((cs) => cs.status === "applied") ?? null,
    [changeSetsQuery.data],
  );

  const dismissMutation = trpc.dismissAgent.useMutation();

  const planSpawn = useSpawnMutation(trpc.spawnArchitectPlan.useMutation, {
    showToast: false,
  });

  const handlePlan = useCallback(() => {
    planSpawn.spawn({ initiativeId });
  }, [initiativeId, planSpawn]);

  const handleDismiss = useCallback(() => {
    if (!planAgent) return;
    dismissMutation.mutate({ id: planAgent.id });
  }, [planAgent, dismissMutation]);

  // Don't render during loading
  if (!phasesLoaded) {
    return null;
  }

  // If phases exist and no change set to show, hide section
  if (phases.length > 0 && !latestChangeSet) {
    return null;
  }

  // Show change set banner when plan agent completed
  if (planAgent?.status === "idle" && latestChangeSet) {
    return (
      <div className="py-4">
        <ChangeSetBanner
          changeSet={latestChangeSet}
          onDismiss={handleDismiss}
        />
      </div>
    );
  }

  return (
    <div className="py-8 text-center space-y-3">
      <p className="text-muted-foreground">No phases yet</p>
      {isPlanRunning ? (
        <div className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
          <Loader2 className="h-3.5 w-3.5 animate-spin" />
          Planning phases...
        </div>
      ) : (
        <div className="flex items-center justify-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={handlePlan}
            disabled={planSpawn.isSpawning}
            className="gap-1.5"
          >
            <Sparkles className="h-3.5 w-3.5" />
            {planSpawn.isSpawning
              ? "Starting..."
              : "Plan Phases"}
          </Button>
          {onAddPhase && (
            <>
              <span className="text-xs text-muted-foreground">or</span>
              <Button
                variant="outline"
                size="sm"
                onClick={onAddPhase}
                className="gap-1.5"
              >
                <Plus className="h-3.5 w-3.5" />
                Add Phase
              </Button>
            </>
          )}
        </div>
      )}
      {planSpawn.isError && (
        <p className="text-xs text-destructive">
          {planSpawn.error}
        </p>
      )}
    </div>
  );
}
