import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/* eslint-disable react/jsx-max-depth */
/* eslint-disable react/jsx-no-bind */
/* eslint-disable react/jsx-props-no-spreading */
import React, { useId, useMemo, useRef } from "react";
import { Input } from "../../../../ui/components/index.js";
import { sharedValueTransformers } from "../../../lib/shared-value-transformers.js";
import { cn } from "../../../lib/utils.js";
import { Command } from "../command/command.js";
import { FormDescription } from "../form-description/form-description.js";
import { FormGroup } from "../form-group/form-group.js";
import { FormLabel } from "../form-label/form-label.js";
import { FormMessageList } from "../form-message/index.js";
import { Popover, PopoverAnchor, PopoverContent } from "../popover/popover.js";
import ValueTransformer from "../value-transformer/value-transformer.js";
import { IdAutocompleteInputContainer } from "./id-autocomplete-input-container.js";
import { IdAutocompleteListOption } from "./id-autocomplete-list-option.js";
import { IdAutocompleteList } from "./id-autocomplete-list.js";
import { useIdAutocomplete } from "./use-id-autocomplete.js";
const IdAutocomplete = React.forwardRef(({ id: idProp, name, className, label, description, value, defaultValue, disabled, placeholder, required, errors, warnings, onChange, onBlur, onClick, onKeyDown, onMouseDown, autoComplete = true, variant = "withValue", maxLength, fetchOptionsCallback, fetchSelectedOptionCallback, isOpenByDefault, // to be used only in stories
initialOptions, renderOption, previewPlaceholder, ...props }, ref) => {
    const prefix = useId();
    const id = idProp ?? `${prefix}-id-autocomplete`;
    const inputRef = useRef(null);
    const mergedRef = (node) => {
        inputRef.current = node;
        if (typeof ref === "function") {
            ref(node);
        }
        else if (ref) {
            ref.current = node;
        }
    };
    const hasWarning = Array.isArray(warnings) && warnings.length > 0;
    const hasError = Array.isArray(errors) && errors.length > 0;
    const { selectedValue, selectedOption, isPopoverOpen, commandListRef, options, isLoading, isLoadingSelectedOption, haveFetchError, commandValue, isFetchSelectedOptionSync, toggleOption, handleOpenChange, onTriggerBlur, handleChange, handleCommandValue, handleFetchSelectedOption, handlePaste, } = useIdAutocomplete({
        autoComplete,
        defaultValue,
        value,
        isOpenByDefault,
        initialOptions,
        onChange,
        onBlur,
        fetchOptions: fetchOptionsCallback,
        fetchSelectedOption: fetchSelectedOptionCallback,
    });
    const handleOptionSelection = (optionValue) => {
        toggleOption(optionValue);
        inputRef.current?.focus();
    };
    const asCard = variant === "withValueAndTitle" ||
        variant === "withValueTitleAndDescription";
    const transformers = useMemo(() => [
        sharedValueTransformers.trimOnBlur(),
        sharedValueTransformers.trimOnEnter(),
    ], []);
    return (_jsxs(FormGroup, { children: [!!label && (_jsx(FormLabel, { htmlFor: id, disabled: disabled, hasError: hasError, required: required, onClick: (e) => {
                    e.preventDefault();
                    e.target.control?.focus();
                }, children: label })), autoComplete && fetchOptionsCallback ? (_jsx(Popover, { open: isPopoverOpen, onOpenChange: handleOpenChange, children: _jsxs(Command, { shouldFilter: false, value: commandValue, onValueChange: handleCommandValue, className: cn("dark:bg-charcoal-900 bg-gray-100"), children: [_jsx(PopoverAnchor, { asChild: true, children: _jsx(IdAutocompleteInputContainer, { id: id, name: name, value: selectedValue, className: className, isLoading: isLoading, haveFetchError: haveFetchError, disabled: disabled, onChange: handleChange, onBlur: onTriggerBlur, onClick: onClick, selectedOption: selectedOption, optionsLength: options.length, handleOpenChange: handleOpenChange, onKeyDown: onKeyDown, onMouseDown: onMouseDown, placeholder: placeholder, hasError: hasError, label: label, required: required, isPopoverOpen: isPopoverOpen, maxLength: maxLength, handlePaste: handlePaste, ...props, ref: mergedRef }) }), asCard &&
                            (renderOption ? (renderOption(selectedOption === undefined && previewPlaceholder
                                ? {
                                    ...previewPlaceholder,
                                }
                                : {
                                    ...selectedOption,
                                    value: selectedOption?.value ?? "",
                                }, {
                                asPlaceholder: selectedOption === undefined,
                                showValue: false,
                                isLoadingSelectedOption,
                                handleFetchSelectedOption: fetchSelectedOptionCallback
                                    ? handleFetchSelectedOption
                                    : undefined,
                                isFetchSelectedOptionSync,
                                className: cn("rounded-t-none pt-2"),
                            })) : (_jsx(IdAutocompleteListOption, { variant: variant, icon: selectedOption?.icon ?? previewPlaceholder?.icon, title: selectedOption?.title ?? previewPlaceholder?.title, path: selectedOption?.path ?? previewPlaceholder?.path, value: selectedOption?.value ?? previewPlaceholder?.value ?? "", description: selectedOption?.description ??
                                    previewPlaceholder?.description, asPlaceholder: selectedOption === undefined, showValue: false, isLoadingSelectedOption: isLoadingSelectedOption, handleFetchSelectedOption: fetchSelectedOptionCallback
                                    ? handleFetchSelectedOption
                                    : undefined, isFetchSelectedOptionSync: isFetchSelectedOptionSync, className: cn("rounded-t-none pt-2") }))), _jsx(PopoverContent, { align: "start", onOpenAutoFocus: (e) => e.preventDefault(), onInteractOutside: (e) => {
                                if (e.target instanceof Element && e.target.id === id) {
                                    e.preventDefault();
                                }
                            }, children: _jsx(IdAutocompleteList, { variant: variant, commandListRef: commandListRef, selectedValue: selectedValue, options: options, toggleOption: handleOptionSelection, renderOption: renderOption, previewPlaceholder: previewPlaceholder }) })] }) })) : (_jsx(ValueTransformer, { transformers: transformers, children: _jsx(Input, { id: id, name: name, value: selectedValue, className: className, disabled: disabled, onChange: handleChange, onBlur: onBlur, onClick: onClick, onMouseDown: onMouseDown, placeholder: placeholder, "aria-invalid": hasError, "aria-label": !label ? "Id Autocomplete" : undefined, "aria-required": required, maxLength: maxLength, ...props, ref: mergedRef }) })), !!description && _jsx(FormDescription, { children: description }), hasWarning && _jsx(FormMessageList, { messages: warnings, type: "warning" }), hasError && _jsx(FormMessageList, { messages: errors, type: "error" })] }));
});
IdAutocomplete.displayName = "IdAutocomplete";
export { IdAutocomplete };
//# sourceMappingURL=id-autocomplete.js.map