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";

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

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

export const AutoComplete = ({
    options = [],
    placeholder = "Type to search...",
    emptyMessage = "No results found.",
    value = null, // Default to `null` instead of `undefined`
    onValueChange,
    disabled = false,
    isLoading = false,
    onSearch,
    setValue,
}: 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); // Trigger onSearch callback
        },
        [onSearch]
    );

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

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

    const handleClear = ()=>{
        setValue('location',"")
        setInputValue("")
        setSelected(null)
    }

    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 font-medium me-5"
                />
                {
                    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 shadow-none",
                        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>
    );
};