import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useConnections } from "@/hooks/use-connections";
import { useAppStore } from "@/stores/app-store";
import { EnvironmentBadge } from "@/components/connections/EnvironmentBadge";

export function ConnectionSelector() {
  const { data: connections } = useConnections();
  const { activeConnectionId, setActiveConnectionId, connectedIds } =
    useAppStore();

  const connectedList = connections?.filter((c) => connectedIds.has(c.id)) ?? [];

  if (connectedList.length === 0) {
    return (
      <div className="text-xs text-muted-foreground px-2">Not connected</div>
    );
  }

  return (
    <Select
      value={activeConnectionId ?? undefined}
      onValueChange={setActiveConnectionId}
    >
      <SelectTrigger className="h-7 w-auto max-w-[280px] text-xs">
        <SelectValue placeholder="Select connection" />
      </SelectTrigger>
      <SelectContent>
        {connectedList.map((conn) => (
          <SelectItem key={conn.id} value={conn.id}>
            <div className="flex items-center gap-1.5">
              {conn.color && (
                <span
                  className="h-2.5 w-2.5 shrink-0 rounded-full"
                  style={{ backgroundColor: conn.color }}
                />
              )}
              {conn.name}
              <EnvironmentBadge environment={conn.environment} size="sm" />
            </div>
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}
