import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/shared/ui/select";
import { useTranslation } from "react-i18next";

interface InfiniteScrollSelectProps<T> {
  value: string;
  onValueChange: (value: string) => void;
  placeholder: string;
  label: string;
  data: T[];
  hasNextPage?: boolean;
  isFetchingNextPage?: boolean;
  fetchNextPage: () => void;
  renderOption: (item: T) => {
    key: string | number;
    value: string;
    label: string;
  };
  isLoading?: boolean;
  className?: string;
}

export function InfiniteScrollSelect<T>({
  value,
  onValueChange,
  placeholder,
  label,
  data,
  hasNextPage,
  isFetchingNextPage,
  fetchNextPage,
  renderOption,
  isLoading = false,
  className = "",
}: InfiniteScrollSelectProps<T>) {
  const { t } = useTranslation();

  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;

    // Scroll oxiriga 50px qolganda keyingi page ni yuklash
    if (
      scrollHeight - scrollTop - clientHeight < 50 &&
      hasNextPage &&
      !isFetchingNextPage
    ) {
      fetchNextPage();
    }
  };

  return (
    <Select onValueChange={onValueChange} value={value} disabled={isLoading}>
      <SelectTrigger
        className={`w-full !h-12 bg-gray-800 border-gray-700 text-white ${className}`}
      >
        <SelectValue placeholder={placeholder} />
      </SelectTrigger>
      <SelectContent className="bg-gray-800 border-gray-700 text-white max-h-[200px] overflow-hidden">
        <SelectGroup>
          <SelectLabel>{label}</SelectLabel>
          <div
            data-radix-select-viewport
            className="overflow-y-auto max-h-[180px]"
            onScroll={handleScroll}
          >
            {data && data?.length === 0 && !isLoading && (
              <div className="text-center py-4 text-gray-400 text-sm">
                {t("Ma'lumot topilmadi")}
              </div>
            )}

            {data.map((item) => {
              const option = renderOption(item);
              return (
                <SelectItem key={option.key} value={option.value}>
                  {option.label}
                </SelectItem>
              );
            })}

            {isFetchingNextPage && (
              <div className="text-center py-2 text-gray-400 text-sm">
                {t("Yuklanmoqda...")}
              </div>
            )}

            {!hasNextPage && data && data.length > 0 && (
              <div className="text-center py-2 text-gray-500 text-xs">
                {t("Barcha ma'lumotlar yuklandi")}
              </div>
            )}
          </div>
        </SelectGroup>
      </SelectContent>
    </Select>
  );
}
