import { useState } from "react";
import { ChevronDown } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { trpc } from "@/lib/trpc";
import { useSpawnMutation } from "@/hooks/useSpawnMutation";

interface SpawnArchitectDropdownProps {
  initiativeId: string;
  initiativeName?: string;
}

export function SpawnArchitectDropdown({
  initiativeId,
}: SpawnArchitectDropdownProps) {
  const [open, setOpen] = useState(false);
  const [successText, setSuccessText] = useState<string | null>(null);

  const handleSuccess = () => {
    setOpen(false);
    setSuccessText("Spawned!");
    setTimeout(() => setSuccessText(null), 2000);
  };

  const discussSpawn = useSpawnMutation(trpc.spawnArchitectDiscuss.useMutation, {
    onSuccess: handleSuccess,
  });

  const planSpawn = useSpawnMutation(trpc.spawnArchitectPlan.useMutation, {
    onSuccess: handleSuccess,
  });

  const isPending = discussSpawn.isSpawning || planSpawn.isSpawning;

  function handleDiscuss() {
    discussSpawn.spawn({ initiativeId });
  }

  function handlePlan() {
    planSpawn.spawn({ initiativeId });
  }

  return (
    <DropdownMenu open={open} onOpenChange={setOpen}>
      <DropdownMenuTrigger asChild>
        <Button variant="outline" size="sm" disabled={isPending}>
          {successText ?? "Spawn Architect"}
          <ChevronDown className="ml-1 h-3 w-3" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start">
        <DropdownMenuItem onClick={handleDiscuss} disabled={isPending}>
          Discuss
        </DropdownMenuItem>
        <DropdownMenuItem onClick={handlePlan} disabled={isPending}>
          Plan
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
