import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { ChevronDown } from "lucide-react";
import { AgentIcon } from "./AgentIconPicker";
import { agentsApi } from "../api/agents";
import { chatApi } from "../api/chat";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandItem, CommandList } from "@/components/ui/command";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { agentRoleColors, agentRoleColorDefault } from "../lib/agent-role-colors";
import type { Agent, AgentRole } from "@paperclipai/shared";

interface ChatAgentSelectorProps {
  companyId: string;
  conversationId: string | null;
  agentId: string | null;
  onAgentChange: (agentId: string | null) => void;
}

export function ChatAgentSelector({
  companyId,
  conversationId,
  agentId,
  onAgentChange,
}: ChatAgentSelectorProps) {
  const [open, setOpen] = useState(false);
  const queryClient = useQueryClient();

  const { data: agents, isLoading } = useQuery({
    queryKey: ["agents", companyId],
    queryFn: () => agentsApi.list(companyId),
    enabled: !!companyId,
  });

  const updateMutation = useMutation({
    mutationFn: (newAgentId: string) =>
      chatApi.updateConversation(conversationId!, { agentId: newAgentId }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["chat", "conversations"] });
    },
  });

  const activeAgent = agents?.find((a) => a.id === agentId);

  const handleSelect = (agent: Agent) => {
    onAgentChange(agent.id);
    if (conversationId) {
      updateMutation.mutate(agent.id);
    }
    setOpen(false);
  };

  if (isLoading) {
    return <Skeleton className="h-7 w-20 rounded" />;
  }

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="ghost"
          size="sm"
          className="h-7 max-w-[120px] gap-1 px-2 text-xs"
          aria-label="Active agent"
        >
          {activeAgent ? (
            <>
              <AgentIcon
                icon={activeAgent.icon}
                className={`h-3.5 w-3.5 ${activeAgent.role ? (agentRoleColors[activeAgent.role as AgentRole] ?? agentRoleColorDefault) : agentRoleColorDefault}`}
              />
              <span className="truncate">{activeAgent.name}</span>
            </>
          ) : (
            <span className="text-muted-foreground">Select agent</span>
          )}
          <ChevronDown className="h-3 w-3 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-[200px] p-0" align="start">
        <Command>
          <CommandList>
            <CommandEmpty>No agents configured</CommandEmpty>
            <CommandGroup>
              {agents?.map((agent) => {
                const colorClass = agent.role
                  ? (agentRoleColors[agent.role as AgentRole] ?? agentRoleColorDefault)
                  : agentRoleColorDefault;
                return (
                  <CommandItem
                    key={agent.id}
                    onSelect={() => handleSelect(agent)}
                    className="flex items-center gap-2"
                  >
                    <AgentIcon icon={agent.icon} className={`h-3.5 w-3.5 ${colorClass}`} />
                    <span className="truncate">{agent.name}</span>
                    <span className="ml-auto text-[11px] text-muted-foreground">{agent.role}</span>
                  </CommandItem>
                );
              })}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}
