import {
    CommandGroup,
    CommandItem,
    CommandList,
    CommandInput,
} from "./ui/command";
import { Command as CommandPrimitive } from "cmdk";
import { useState, useRef, useCallback } from "react";


import { Check } from "lucide-react";
import { cn } from "@/lib/utils";
import { Icons } from "./icons";
import { useRouter } from "next/navigation";

type Option = {
    value: string;
    label: string;
};

type AutoCompleteProps = {
    options: Option[];
    emptyMessage: string;
    value?: Option | null;
    onValueChange?: (value: Option | null) => void;
    isLoading?: boolean;
    disabled?: boolean;
    placeholder?: string;
    onSearch?: (query: string) => void;
    setValue: any;
    setSharedata: any
};

export const Search = ({
    options = [],
    placeholder = "Type to search...",
    value = null,
    onValueChange,
    disabled = false,
    isLoading = false,
    onSearch,
    setSharedata,
}: AutoCompleteProps) => {
    const inputRef = useRef<HTMLInputElement>(null);
    const [isOpen, setOpen] = useState(false);
    const [selected, setSelected] = useState<Option | null>(value);
    const [inputValue, setInputValue] = useState<string>(value?.label || "");


    const handleInputChange = useCallback(
        (newValue: string) => {
            setInputValue(newValue);
            onSearch?.(newValue);
        },
        [onSearch]
    );

    const handleBlur = useCallback(() => {
        setOpen(false);
        setInputValue(selected?.label || "");
    }, [selected]);

    const handleSelectOption = useCallback(
        (selectedOption: Option) => {
            setInputValue(selectedOption.label);
            // setValue('title',selectedOption.label)
            setSelected(selectedOption);
            onValueChange?.(selectedOption);
        },
        [onValueChange]
    );

    const handleClear = () => {
        setInputValue("")
        setSelected(null)
        setSharedata({
            access_to: "",
            access_type: "View"
        })
    }

    return (
        <CommandPrimitive>
            <div className="relative">
                <CommandInput
                    ref={inputRef}
                    value={inputValue}
                    onValueChange={!isLoading ? handleInputChange : undefined}
                    onBlur={handleBlur}
                    onFocus={() => setOpen(true)}
                    placeholder={placeholder}
                    disabled={disabled}
                    className="text-sm  placeholder:font-normal font-medium"
                />
                {
                    inputValue && <span className="absolute right-3 top-[17px] cursor-pointer" onClick={handleClear}><Icons.CrossIcon2 /></span>
                }
            </div>
            <div className="relative mt-1">
                <div
                    className={cn(
                        "animate-in fade-in-0 zoom-in-95 absolute top-0 z-10 w-full  rounded-sm bg-white border shadow-sm",
                        isOpen ? "block" : "hidden"
                    )}
                >
                    <CommandList className="rounded-sm">
                        {isLoading && (
                            <CommandPrimitive.Loading>
                                <div className="p-2 text-black text-center">
                                    {/* <Skeleton className="h-8 w-full" /> */}
                                    Loading...
                                </div>
                            </CommandPrimitive.Loading>
                        )}
                        {!isLoading && options.length > 0 && (
                            <CommandGroup>
                                {options.map((option) => {
                                    const isSelected = selected?.value === option.value;
                                    return (
                                        <CommandItem
                                            key={option.value}
                                            value={option.label}
                                            onMouseDown={(event) => {
                                                event.preventDefault();
                                                event.stopPropagation();
                                            }}
                                            onSelect={() => handleSelectOption(option)}
                                            className={cn(
                                                "flex w-full font-normal  items-center gap-2 px-3 py-2 text-sm hover:bg-gray-100",
                                                isSelected ? "font-normal bg-gray-200" : null
                                            )}
                                        >
                                            {isSelected && <Check className="w-4 theme-color" />}
                                            {option.label}
                                        </CommandItem>
                                    );
                                })}
                            </CommandGroup>
                        )}
                        {/* {!isLoading && options.length === 0 && (
                            <CommandPrimitive.Empty className="select-none px-3 py-2 text-center text-sm text-gray-500">
                                {emptyMessage}
                            </CommandPrimitive.Empty>
                        )} */}
                    </CommandList>
                </div>
            </div>
        </CommandPrimitive>
    );
};