"use client";
import React, { useRef, useState, useCallback, useEffect } from "react";
import { Loader2 } from "lucide-react";
import * as SelectPrimitive from "@radix-ui/react-select";
import { PopoverContent } from "@/components/ui/popover";
import {
    Command,
    CommandEmpty,
    CommandInput,
    CommandList,
    CommandLoading
} from "@/components/ui/command";
import { useSelectContext } from "@/components/ui/field/select/select.context";
import { cn } from "@/lib/utils/cn";

export type SelectContentProps = React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content> & {
    searchable?: boolean;
    searchPlaceholder?: string;
    emptyMessage?: string;
    loading?: boolean;
    search?: string;
    onSearch?: (search: string) => void;
    onScrollReachBottom?: () => void;
};

export const SelectContent = React.forwardRef<HTMLDivElement, SelectContentProps>((props, ref) => {
    const {
        className,
        children,
        loading,
        position = "popper",
        searchable = false,
        searchPlaceholder = "Search...",
        emptyMessage = "No results found.",
        search,
        onSearch,
        onScrollReachBottom,
        ...rest
    } = props;

    const { multiple } = useSelectContext();

    const [internalSearch, setInternalSearch] = useState("");

    const listRef = useRef<HTMLDivElement>(null);

    const handleSearchChange = useCallback((value: string) => {
        setInternalSearch(value);

        if(!onSearch) {
            return;
        }

        onSearch(value);
    }, [onSearch]);

    const handleScrollReachBottom = useCallback(() => {
        if(!onScrollReachBottom) {
            return;
        }

        const el = listRef.current;

        if(!el) {
            return;
        }

        const isBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 4;

        if(isBottom) {
            onScrollReachBottom();
        }
    }, [onScrollReachBottom]);

    useEffect(() => {
        setInternalSearch(search || "");
    }, [search]);

    return (
        <>
            {/*<div style={{ display: "none" }}>
                <Command>
                    <CommandList>
                        {children}
                    </CommandList>
                </Command>
            </div>*/}

            <PopoverContent
              {...rest}
              ref={ref}
              forceMount
              className={cn("w-[var(--radix-popover-trigger-width)] p-0", className)}
              align="start">
                <Command
                  value={internalSearch}
                  // onValueChange={handleSearchChange}
                  >
                    {searchable && (
                        <CommandInput
                          placeholder={searchPlaceholder}
                          value={search}
                          onValueChange={handleSearchChange} />
                    )}

                    <CommandList
                      ref={listRef}
                      onScroll={handleScrollReachBottom}>
                        <CommandEmpty>{emptyMessage}</CommandEmpty>

                        {children}

                        {loading && (
                            <CommandLoading>
                                <div className="flex justify-center">
                                    <Loader2 className="animate-spin text-muted-foreground" />
                                </div>
                            </CommandLoading>
                        )}
                    </CommandList>
                </Command>
            </PopoverContent>
        </>
    );
});

SelectContent.displayName = "SelectContent";
