"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useMemo, useCallback } from "react";
import { Check, ChevronsUpDown, Globe, Users, Search, Loader2 } from "lucide-react";
import { useUserTeams, useTeamSearch } from "../../../hooks/teams/index.js";
import { useDebounce } from "../../../hooks/useDebounce.js";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../ui/select.js";
import { Button } from "../../ui/button.js";
import { Skeleton } from "../../ui/skeleton.js";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandSeparator
} from "../../ui/command.js";
import {
  Popover,
  PopoverContent,
  PopoverTrigger
} from "../../ui/popover.js";
import { cn } from "../../../lib/utils/index.js";
import { sel } from "../../../lib/test/index.js";
function TeamSelector({
  selectedTeamId,
  onTeamChange,
  bypassMode,
  disabled = false
}) {
  const [open, setOpen] = useState(false);
  const [searchValue, setSearchValue] = useState("");
  const debouncedSearch = useDebounce(searchValue, 300);
  const { teams: userTeams, isLoading: isLoadingUserTeams } = useUserTeams();
  const {
    teams: allTeams,
    totalCount,
    isLoading: isLoadingAllTeams
  } = useTeamSearch(debouncedSearch, bypassMode);
  const selectedTeam = useMemo(() => {
    if (!selectedTeamId) return null;
    const fromUser = userTeams.find((t) => t.id === selectedTeamId);
    if (fromUser) return fromUser;
    const fromAll = allTeams.find((t) => t.id === selectedTeamId);
    if (fromAll) return { id: fromAll.id, name: fromAll.name, slug: "" };
    return null;
  }, [selectedTeamId, userTeams, allTeams]);
  const handleSelect = useCallback(
    (teamId) => {
      onTeamChange(teamId);
      setOpen(false);
      setSearchValue("");
    },
    [onTeamChange]
  );
  if (!bypassMode && isLoadingUserTeams) {
    return /* @__PURE__ */ jsx(Skeleton, { className: "h-9 w-full", "data-cy": sel("devtools.apiExplorer.team.loading") });
  }
  if (!bypassMode) {
    return /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", "data-cy": sel("devtools.apiExplorer.team.container"), children: [
      /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: "Team Context" }),
      /* @__PURE__ */ jsxs(
        Select,
        {
          value: selectedTeamId || "none",
          onValueChange: (value) => onTeamChange(value === "none" ? null : value),
          disabled,
          children: [
            /* @__PURE__ */ jsx(SelectTrigger, { className: "w-full", "data-cy": sel("devtools.apiExplorer.team.trigger"), children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Select team..." }) }),
            /* @__PURE__ */ jsx(SelectContent, { children: userTeams.map((team) => /* @__PURE__ */ jsx(SelectItem, { value: team.id, "data-cy": sel("devtools.apiExplorer.team.option", { slug: team.slug }), children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(Users, { className: "h-4 w-4 text-muted-foreground" }),
              /* @__PURE__ */ jsx("span", { children: team.name }),
              /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground", children: [
                "(",
                team.slug,
                ")"
              ] })
            ] }) }, team.id)) })
          ]
        }
      ),
      !selectedTeamId && /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", "data-cy": sel("devtools.apiExplorer.team.error"), children: "Team required for non-bypass requests" })
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", "data-cy": sel("devtools.apiExplorer.team.container"), children: [
    /* @__PURE__ */ jsxs("label", { className: "text-xs font-medium text-muted-foreground", children: [
      "Filter by Team (optional)",
      totalCount > 0 && /* @__PURE__ */ jsxs("span", { className: "ml-2 text-muted-foreground/70", children: [
        totalCount,
        " teams available"
      ] })
    ] }),
    /* @__PURE__ */ jsxs(Popover, { open, onOpenChange: setOpen, children: [
      /* @__PURE__ */ jsx(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
        Button,
        {
          variant: "outline",
          role: "combobox",
          "aria-expanded": open,
          className: cn(
            "w-full justify-between font-normal",
            disabled && "opacity-50 cursor-not-allowed"
          ),
          disabled,
          "data-cy": sel("devtools.apiExplorer.team.bypassTrigger"),
          children: [
            selectedTeamId === null ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-muted-foreground", children: [
              /* @__PURE__ */ jsx(Globe, { className: "h-4 w-4" }),
              /* @__PURE__ */ jsx("span", { children: "Cross-team (all teams)" })
            ] }) : selectedTeam ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(Users, { className: "h-4 w-4 text-muted-foreground" }),
              /* @__PURE__ */ jsx("span", { children: selectedTeam.name })
            ] }) : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "Select team to filter..." }),
            /* @__PURE__ */ jsx(ChevronsUpDown, { className: "ml-2 h-4 w-4 shrink-0 opacity-50" })
          ]
        }
      ) }),
      /* @__PURE__ */ jsx(
        PopoverContent,
        {
          className: "p-0",
          align: "start",
          style: { width: "var(--radix-popover-trigger-width)" },
          children: /* @__PURE__ */ jsxs(Command, { shouldFilter: false, children: [
            /* @__PURE__ */ jsx(
              CommandInput,
              {
                placeholder: "Search teams by name or owner...",
                value: searchValue,
                onValueChange: setSearchValue,
                "data-cy": sel("devtools.apiExplorer.team.search")
              }
            ),
            isLoadingAllTeams ? /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-center py-6", children: [
              /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin mr-2" }),
              /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: "Searching teams..." })
            ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx(CommandEmpty, { children: /* @__PURE__ */ jsxs("div", { className: "py-2 text-sm", children: [
                /* @__PURE__ */ jsx(Search, { className: "h-4 w-4 mx-auto mb-2 opacity-50" }),
                /* @__PURE__ */ jsx("p", { children: "No teams found" }),
                debouncedSearch && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-1", children: "Try a different search term" })
              ] }) }),
              /* @__PURE__ */ jsxs(CommandGroup, { className: "max-h-64 overflow-auto", children: [
                /* @__PURE__ */ jsxs(
                  CommandItem,
                  {
                    value: "cross-team",
                    onSelect: () => handleSelect(null),
                    "data-cy": sel("devtools.apiExplorer.team.crossTeam"),
                    children: [
                      /* @__PURE__ */ jsx(
                        Check,
                        {
                          className: cn(
                            "mr-2 h-4 w-4",
                            selectedTeamId === null ? "opacity-100" : "opacity-0"
                          )
                        }
                      ),
                      /* @__PURE__ */ jsx(Globe, { className: "mr-2 h-4 w-4 text-muted-foreground" }),
                      /* @__PURE__ */ jsxs("div", { className: "flex flex-col", children: [
                        /* @__PURE__ */ jsx("span", { children: "Cross-team (all teams)" }),
                        /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "Access data from all teams without filtering" })
                      ] })
                    ]
                  }
                ),
                allTeams.length > 0 && /* @__PURE__ */ jsx(CommandSeparator, { className: "my-1" }),
                allTeams.map((team) => /* @__PURE__ */ jsxs(
                  CommandItem,
                  {
                    value: team.id,
                    onSelect: () => handleSelect(team.id),
                    "data-cy": sel("devtools.apiExplorer.team.bypassOption", { id: team.id }),
                    children: [
                      /* @__PURE__ */ jsx(
                        Check,
                        {
                          className: cn(
                            "mr-2 h-4 w-4",
                            selectedTeamId === team.id ? "opacity-100" : "opacity-0"
                          )
                        }
                      ),
                      /* @__PURE__ */ jsx(Users, { className: "mr-2 h-4 w-4 text-muted-foreground" }),
                      /* @__PURE__ */ jsxs("div", { className: "flex flex-col flex-1 min-w-0", children: [
                        /* @__PURE__ */ jsx("span", { className: "truncate", children: team.name }),
                        /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground truncate", children: [
                          team.owner.name,
                          " \xB7 ",
                          team.memberCount,
                          " members"
                        ] })
                      ] })
                    ]
                  },
                  team.id
                ))
              ] })
            ] })
          ] })
        }
      )
    ] })
  ] });
}
export {
  TeamSelector
};
