"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SelectInput = void 0;
const react_1 = __importStar(require("react"));
const Popover = __importStar(require("@radix-ui/react-popover"));
const Text_1 = require("../Text");
const inlines_1 = require("inlines");
const icons_1 = require("../../icons");
const varsUtilities_1 = require("../../varsUtilities");
const react_remove_scroll_1 = require("react-remove-scroll");
const useControllableState_1 = require("../../hooks/useControllableState");
const utils_1 = require("../../utils");
const inputToString = (input) => {
    return typeof input === 'object'
        ? typeof input.label === 'string'
            ? input.label
            : input.value
        : '';
};
function SelectInput({ value: valueProp, defaultValue: defaultValueProp, onChange: onChangeProp, clearbutton, options, placeholder, onOpen = () => {
    return undefined;
}, size = 'normal', style, searchable = false, hugContent = false, autoFocus, }) {
    const [value, setValue] = (0, useControllableState_1.useControllableState)({
        prop: valueProp,
        defaultProp: defaultValueProp,
        onChange: onChangeProp,
    });
    const [open, setOpen] = (0, react_1.useState)(false);
    const [inputValue, setInputValue] = (0, react_1.useState)('');
    const [inputValueChanged, setInputValueChanged] = (0, react_1.useState)(false);
    const inputRef = (0, react_1.useRef)(null);
    const [activeIndex, setActiveIndex] = (0, react_1.useState)(null);
    const filteredOptions = inputValueChanged && inputValue
        ? options.filter((e) => {
            const f = typeof e.label === 'string' ? e.label : e.value;
            return f
                .toLocaleLowerCase()
                .includes(inputToString(inputValue).toLocaleLowerCase());
        })
        : options;
    const Component = searchable ? inlines_1.styled.input : inlines_1.styled.div;
    const componentProps = searchable
        ? {
            value: size === 'small' && inputToString(inputValue).length >= 12
                ? inputToString(inputValue).split('').slice(0, 10).join('') + '...'
                : inputToString(inputValue),
            placeholder,
        }
        : {
            children: inputToString(inputValue)
                ? size === 'small' && inputToString(inputValue).length >= 12
                    ? inputToString(inputValue).split('').slice(0, 10).join('') + '...'
                    : inputToString(inputValue)
                : placeholder,
        };
    function handleSelectItem(index) {
        // && or || or just one of them idk TODO
        if (value === filteredOptions[index].value ||
            inputValue === filteredOptions[index]) {
            setValue('');
            setInputValue('');
            setOpen(false);
            return;
        }
        setValue(filteredOptions[index].value);
        setInputValue(filteredOptions[index]);
        setInputValueChanged(false);
        setOpen(false);
        setActiveIndex(null);
    }
    function handleClose() {
        setInputValueChanged(false);
        setInputValue(options.find((e) => e.value === value));
        setOpen(false);
        setActiveIndex(null);
    }
    function handleOpen() {
        setOpen(true);
        onOpen();
        if (searchable) {
            // inputRef.current?.select()
        }
    }
    (0, react_1.useEffect)(() => {
        setInputValue(options.find((e) => e.value === value));
    }, [value]);
    const [hug, setHug] = (0, react_1.useState)(inputRef.current?.offsetWidth);
    (0, react_1.useEffect)(() => {
        setHug(inputRef.current?.offsetWidth);
    }, [inputRef.current]);
    (0, react_1.useEffect)(() => {
        if (autoFocus) {
            inputRef.current.focus();
        }
    }, []);
    return (react_1.default.createElement(Popover.Root, { open: open },
        react_1.default.createElement(Popover.Anchor, { asChild: true },
            react_1.default.createElement(inlines_1.styled.div, { style: {
                    position: 'relative',
                    width: hugContent ? hug : size === 'small' ? '60%' : '100%',
                    // width: 'fit-content',
                    display: 'block',
                    ...style,
                } },
                react_1.default.createElement(Component, { ...componentProps, tabIndex: 0, ref: inputRef, onClick: () => {
                        handleOpen();
                    }, onFocus: () => {
                        handleOpen();
                    }, onChange: (e) => {
                        setInputValue({ value: e.target.value });
                        setInputValueChanged(true);
                        setActiveIndex(null);
                    }, onKeyDown: (e) => {
                        if (open && e.key === 'ArrowDown') {
                            e.preventDefault();
                            const newIndex = activeIndex === null
                                ? 0
                                : Math.min(activeIndex + 1, filteredOptions.length - 1);
                            setActiveIndex(newIndex);
                            document
                                .querySelector(`#combobox-item-${newIndex}`)
                                .scrollIntoView({ block: 'nearest' });
                        }
                        if (open && e.key === 'ArrowUp') {
                            e.preventDefault();
                            const newIndex = activeIndex === null ? 0 : Math.max(0, activeIndex - 1);
                            setActiveIndex(newIndex);
                            document
                                .querySelector(`#combobox-item-${newIndex}`)
                                .scrollIntoView({ block: 'nearest' });
                        }
                        if (e.key === 'Enter') {
                            e.preventDefault();
                            if (open) {
                                if (activeIndex !== null) {
                                    handleSelectItem(activeIndex);
                                }
                            }
                            else {
                                handleOpen();
                            }
                        }
                    }, placeholder: placeholder, style: {
                        cursor: searchable ? 'auto' : 'pointer',
                        boxSizing: 'border-box',
                        outline: 'none',
                        width: '100%',
                        position: 'relative',
                        padding: size === 'small' ? '6px 40px 6px 12px' : '8px 40px 8px 12px',
                        fontSize: 14,
                        lineHeight: '24px',
                        background: 'transparent',
                        fontFamily: 'Inter',
                        height: 42,
                        fontWeight: '500',
                        color: searchable
                            ? (0, varsUtilities_1.color)('content', 'default', 'primary')
                            : inputToString(inputValue)
                                ? (0, varsUtilities_1.color)('content', 'default', 'primary')
                                : (0, varsUtilities_1.color)('content', 'default', 'secondary'),
                        borderRadius: 8,
                        '&::placeholder': {
                            color: (0, varsUtilities_1.color)('content', 'default', 'secondary'),
                        },
                        ...(open
                            ? {
                                border: `1px solid ${(0, varsUtilities_1.color)('inputBorder', 'active', 'default')}`,
                                boxShadow: `0 0 0 2px ${(0, varsUtilities_1.color)('border', 'brand', 'subtle')}`,
                            }
                            : {
                                border: `1px solid ${(0, varsUtilities_1.color)('inputBorder', 'neutralNormal', 'default')}`,
                                '&:hover': {
                                    border: `1px solid ${(0, varsUtilities_1.color)('inputBorder', 'neutralHover', 'default')}`,
                                },
                            }),
                        whiteSpace: hugContent ? 'nowrap' : 'initial',
                        overflow: hugContent ? 'hidden' : 'initial',
                        textOverflow: hugContent ? 'ellipsis' : 'initial',
                    } }),
                inputValue && value && clearbutton && (react_1.default.createElement(icons_1.IconClose, { onClick: (e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        setInputValue(() => {
                            return options.find(() => '' === value);
                        });
                        setActiveIndex(0);
                        setValue('');
                    }, style: { position: 'absolute', top: 10, right: 40 } })),
                react_1.default.createElement("span", { style: {
                        pointerEvents: 'none',
                        position: 'absolute',
                        right: 12,
                        top: 10,
                    } },
                    react_1.default.createElement(icons_1.IconChevronDown, { color: "default" })))),
        react_1.default.createElement(Popover.Portal, null,
            react_1.default.createElement(react_remove_scroll_1.RemoveScroll, { allowPinchZoom: true },
                react_1.default.createElement(Popover.Content, { onInteractOutside: (e) => {
                        if (e.target === inputRef?.current) {
                            e.preventDefault();
                        }
                        else {
                            handleClose();
                        }
                    }, onOpenAutoFocus: (e) => {
                        e.preventDefault();
                    }, onCloseAutoFocus: (e) => {
                        e.preventDefault();
                    }, sideOffset: 8, asChild: true },
                    react_1.default.createElement(inlines_1.styled.div, { style: {
                            boxSizing: 'border-box',
                            overflowY: 'auto',
                            maxHeight: 'min(300px, calc(var(--radix-popover-content-available-height) - 16px))',
                            width: 'var(--radix-popover-trigger-width)',
                            border: `1px solid ${(0, varsUtilities_1.color)('border', 'default', 'strong')}`,
                            borderRadius: 8,
                            padding: 8,
                            background: (0, varsUtilities_1.color)('standalone', 'modal', 'default'),
                            boxShadow: '0px 2px 8px -1px rgba(27, 36, 44, 0.08), 0px 2px 2px -1px rgba(27, 36, 44, 0.04)',
                        } }, filteredOptions.length ? (filteredOptions.map((item, index) => (react_1.default.createElement(inlines_1.styled.div, { id: `combobox-item-${index}`, style: {
                            marginTop: 2,
                            cursor: 'pointer',
                            //TODO is it this?
                            background: index === activeIndex
                                ? (0, varsUtilities_1.color)('action', 'system', 'hover')
                                : item.value === value
                                    ? (0, varsUtilities_1.color)('action', 'primary', 'subtleSelected')
                                    : 'transparent',
                            //Or this
                            // background:
                            //   item.value === value
                            //     ? color('action', 'primary', 'subtleSelected')
                            //     : index === activeIndex
                            //     ? color('action', 'system', 'hover')
                            //     : 'transparent',
                            padding: '4px 12px 4px 42px',
                            borderRadius: 8,
                            position: 'relative',
                            scrollMargin: '8px 0',
                            color: (0, varsUtilities_1.color)('content', item.value === value ? 'brand' : 'default', 'primary'),
                            '&:active': {
                                background: item.value === value
                                    ? (0, varsUtilities_1.color)('action', 'primary', 'subtleSelected')
                                    : (0, varsUtilities_1.color)('action', 'system', 'active'),
                            },
                            [utils_1.BpTablet]: {
                                background: item.value === value
                                    ? (0, varsUtilities_1.color)('action', 'primary', 'subtleSelected')
                                    : 'transparent',
                            },
                        }, onClick: () => {
                            handleSelectItem(index);
                        }, onPointerMove: () => {
                            setActiveIndex(index);
                        }, key: item.value },
                        item.value === value && (react_1.default.createElement("span", { style: { position: 'absolute', left: 12, top: 6 } },
                            react_1.default.createElement(icons_1.IconCheckLarge, { color: "inherit" }))),
                        react_1.default.createElement(Text_1.Text, { size: 14, weight: "medium", color: "inherit" }, item.label ?? item.value))))) : (react_1.default.createElement("div", { style: {
                            position: 'relative',
                            background: 'transparent',
                            padding: '4px 12px 4px 42px',
                        } },
                        react_1.default.createElement("span", { style: { position: 'absolute', left: 12, top: 6 } },
                            react_1.default.createElement(icons_1.IconEmojiSad, { color: "default" })),
                        react_1.default.createElement(Text_1.Text, { color: "default", size: 14, weight: "medium" }, "No item found")))))))));
}
exports.SelectInput = SelectInput;
//# sourceMappingURL=SelectInput.js.map