import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useDebouncedValue } from "@mantine/hooks";
import { Building2, Check, ChevronsUpDown, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/shared/common/ui/button";
import { Badge } from "@/shared/common/ui/badge";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/shared/common/ui/popover";
import {
  Command,
  CommandEmpty,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/shared/common/ui/command";
import { cn } from "@/super-admin/lib/utils";
import { useLocalizedName } from "@/shared/common/localizedName";
import { getOrganizationsWithAdminFlag } from "@/shared/services/organizationsService";
import { OrganizationDto } from "@/shared/dto/organization/organizationDto";
import { ORG_PICKER_KEY } from "@/super-admin/hooks/useOrgAdmins";

interface OrgPickerProps {
  value: OrganizationDto | null;
  onChange: (org: OrganizationDto) => void;
}

/** Searchable organization combobox — server-side name search, shows admin counts. */
export function OrgPicker({ value, onChange }: OrgPickerProps) {
  const { t } = useTranslation();
  const localizedName = useLocalizedName();
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState("");
  const [debouncedSearch] = useDebouncedValue(search, 300);

  const {
    data: orgsResponse,
    isLoading,
    isError,
    refetch,
  } = useQuery({
    queryKey: [ORG_PICKER_KEY, debouncedSearch],
    queryFn: async () => {
      const { data } = await getOrganizationsWithAdminFlag({
        take: 50,
        skip: 0,
        name: debouncedSearch || undefined,
      });
      return {
        count: (data?.count ?? 0) as number,
        items: (data?.items ?? []) as OrganizationDto[],
      };
    },
    staleTime: 5 * 60 * 1000,
    retry: false,
  });

  const orgs = orgsResponse?.items ?? [];

  // default to the first org that already has admins (initial load only,
  // never while the user is searching)
  useEffect(() => {
    if (value || debouncedSearch || !orgs.length) return;
    const firstWithAdmins = orgs.find((org) => (org.adminsCount ?? 0) > 0);
    if (firstWithAdmins) onChange(firstWithAdmins);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [orgsResponse]);

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          aria-expanded={open}
          className="w-full sm:w-[360px] justify-between font-normal"
        >
          <span className="flex items-center gap-2 truncate">
            <Building2 className="h-4 w-4 shrink-0 text-muted-foreground" />
            {value ? (
              <span className="truncate">{localizedName(value.name)}</span>
            ) : (
              <span className="text-muted-foreground">
                {t("orgAdmins.selectOrg")}
              </span>
            )}
          </span>
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-[360px] p-0" align="start">
        <Command shouldFilter={false}>
          <CommandInput
            placeholder={t("orgAdmins.searchOrgs")}
            value={search}
            onValueChange={setSearch}
          />
          <CommandList>
            {isLoading ? (
              <div className="flex items-center justify-center py-6">
                <Loader2 className="h-5 w-5 animate-spin text-primary" />
              </div>
            ) : isError ? (
              <div className="flex flex-col items-center gap-2 py-6 text-sm text-red-600 dark:text-red-400">
                {t("orgAdmins.pickerError")}
                <Button variant="outline" size="sm" onClick={() => refetch()}>
                  {t("common.retry")}
                </Button>
              </div>
            ) : (
              <>
                <CommandEmpty>{t("orgAdmins.noOrgsFound")}</CommandEmpty>
                {orgs.map((org) => (
                  <CommandItem
                    key={org.id}
                    value={org.id}
                    onSelect={() => {
                      onChange(org);
                      setOpen(false);
                    }}
                    className="flex items-center justify-between gap-2"
                  >
                    <span className="flex items-center gap-2 truncate">
                      <Check
                        className={cn(
                          "h-4 w-4 shrink-0",
                          value?.id === org.id ? "opacity-100" : "opacity-0",
                        )}
                      />
                      <span className="truncate">
                        {localizedName(org.name)}
                      </span>
                    </span>
                    {(org.adminsCount ?? 0) > 0 ? (
                      <Badge
                        variant="outline"
                        className="shrink-0 border-emerald-300 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-300"
                      >
                        {t("orgAdmins.adminsCount", {
                          count: org.adminsCount ?? 0,
                        })}
                      </Badge>
                    ) : (
                      <Badge
                        variant="outline"
                        className="shrink-0 border-amber-300 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-300"
                      >
                        {t("orgAdmins.noAdmins")}
                      </Badge>
                    )}
                  </CommandItem>
                ))}
              </>
            )}
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}
