import { ChevronsUpDown, Globe } from "lucide-react";
import type { ConnectorSummary } from "@/ipc/types";
import { cn } from "@/lib/utils";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuLabel,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

interface ConnectorPickerProps {
  connectors: ConnectorSummary[];
  selectedConnector: ConnectorSummary | null;
  onSelectConnector: (connector: ConnectorSummary | null) => void;
  emptyLabel: string;
  menuLabel: string;
  dataTestId: string;
  className?: string;
  selectedClassName?: string;
  unselectedClassName?: string;
}

export function ConnectorPicker({
  connectors,
  selectedConnector,
  onSelectConnector,
  emptyLabel,
  menuLabel,
  dataTestId,
  className,
  selectedClassName,
  unselectedClassName,
}: ConnectorPickerProps) {
  return (
    <DropdownMenu>
      <DropdownMenuTrigger
        className={cn(
          "cursor-pointer px-2 py-1 text-xs font-medium rounded-lg transition-colors flex items-center gap-1.5 max-w-[200px]",
          selectedConnector ? selectedClassName : unselectedClassName,
          className,
        )}
        data-testid={dataTestId}
      >
        <Globe size={14} />
        <span className="truncate">
          {selectedConnector ? selectedConnector.name : emptyLabel}
        </span>
        <ChevronsUpDown size={12} className="opacity-60 shrink-0" />
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start" className="w-72">
        <DropdownMenuLabel>{menuLabel}</DropdownMenuLabel>
        <DropdownMenuSeparator />
        <DropdownMenuRadioGroup
          value={selectedConnector ? String(selectedConnector.id) : "none"}
          onValueChange={(value) => {
            if (value === "none") {
              onSelectConnector(null);
              return;
            }
            onSelectConnector(
              connectors.find((connector) => connector.id === Number(value)) ??
                null,
            );
          }}
        >
          <DropdownMenuRadioItem value="none">
            {emptyLabel}
          </DropdownMenuRadioItem>
          {connectors.map((connector) => (
            <DropdownMenuRadioItem
              key={connector.id}
              value={String(connector.id)}
            >
              <span className="truncate">{connector.name}</span>
            </DropdownMenuRadioItem>
          ))}
        </DropdownMenuRadioGroup>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
