"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.MultiSelect = 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 hooks_1 = require("../../hooks");
const ScrollArea_1 = require("../ScrollArea");
const Tag_1 = require("../Tag");
const utils_1 = require("../../utils");
function MultiSelect({ value: valueProp = [], defaultValue: defaultValueProp, options, placeholder, style, onChange: onChangeProp, onOpen = () => {
    return undefined;
}, hugContent, searchable = true, autoFocus, }) {
    const inputRef = (0, react_1.useRef)(null);
    const textRef = (0, react_1.useRef)(null);
    const [open, setOpen] = (0, react_1.useState)(false);
    const [hug, setHug] = (0, react_1.useState)(inputRef.current?.offsetWidth);
    const [searchInput, setSearchInput] = (0, react_1.useState)('');
    const [value, setValue] = (0, hooks_1.useControllableState)({
        prop: valueProp,
        defaultProp: defaultValueProp,
        onChange: onChangeProp,
    });
    const [inputValue, setInputValue] = (0, react_1.useState)(() => {
        return options.filter((option) => value.includes(option.value));
    });
    const [activeIndex, setActiveIndex] = (0, react_1.useState)(null);
    const filteredOptions = searchable && searchInput !== ''
        ? options
            .filter((item) => !inputValue.map((thing) => thing.value).includes(item.value))
            .filter((item) => {
            return item.label
                .toString()
                .toLocaleLowerCase()
                .includes(searchInput.toLocaleLowerCase());
        })
        : options.filter((item) => !inputValue.map((thing) => thing.value).includes(item.value));
    function handleSelectItem(index) {
        setValue([...value, filteredOptions[index].value]);
        setInputValue([...inputValue, filteredOptions[index]]);
        setActiveIndex(null);
        setSearchInput('');
    }
    function handleClose() {
        // setInputValue(options.filter((option) => value.includes(option.value)))
        setOpen(false);
        setActiveIndex(null);
    }
    function handleOpen() {
        if (searchable) {
            textRef.current.focus();
        }
        setOpen(true);
        onOpen();
    }
    (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("div", { style: {
                    position: 'relative',
                    maxWidth: hugContent ? hug : '100%',
                } },
                react_1.default.createElement(inlines_1.styled.div, { tabIndex: 0, onClick: () => {
                        handleOpen();
                    }, onFocus: () => {
                        handleOpen();
                    }, value: inputValue, ref: inputRef, onChange: (e) => {
                        // e.preventDefault()
                        // e.stopPropagation()
                        // setInputValue([...inputValue, e.target.value])
                        // setActiveIndex(null)
                    }, onKeyDown: (e) => {
                        if (open && e.key === 'ArrowDown') {
                            e.preventDefault();
                            const newIndex = activeIndex === null
                                ? 0
                                : Math.min(activeIndex + 1, options.length - 1);
                            setActiveIndex(newIndex);
                        }
                        if (open && e.key === 'ArrowUp') {
                            e.preventDefault();
                            const newIndex = activeIndex === null ? 0 : Math.max(0, activeIndex - 1);
                            setActiveIndex(newIndex);
                        }
                        if (e.key === 'Enter') {
                            e.preventDefault();
                            if (open) {
                                if (activeIndex !== null) {
                                    handleSelectItem(activeIndex);
                                }
                            }
                            else {
                                handleOpen();
                            }
                        }
                        // if (e.key === 'Backspace') {
                        //   e.preventDefault()
                        //   if (
                        //     searchInput === '' &&
                        //     value instanceof Array &&
                        //     inputValue instanceof Array
                        //   ) {
                        //     setValue(value.pop())
                        //     setInputValue(inputValue.pop())
                        //     console.log(
                        //       typeof value,
                        //       value,
                        //       typeof inputValue,
                        //       inputValue
                        //     )
                        //   }
                        // }
                    }, placeholder: placeholder, style: {
                        boxSizing: 'border-box',
                        outline: 'none',
                        width: '100%',
                        padding: '8px 40px 8px 12px',
                        fontSize: 14,
                        lineHeight: '24px',
                        background: 'transparent',
                        fontFamily: 'Inter',
                        minHeight: 42,
                        cursor: 'pointer',
                        fontWeight: '500',
                        color: inputValue.length > 0
                            ? (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',
                        ...style,
                    } },
                    react_1.default.createElement(inlines_1.styled.div, { onClick: () => {
                            handleOpen();
                        }, style: {
                            // border: '1px solid red',
                            marginTop: '8px 40px 8px 12px',
                            display: 'flex',
                            flexWrap: 'wrap',
                            flexDirection: 'row',
                            gap: 8,
                        } },
                        inputValue.map((v) => (react_1.default.createElement(Tag_1.Tag, { style: { display: 'inline-flex', flexGrow: 0 }, key: v.value, onClose: () => {
                                setValue(value.filter((value) => value !== v.value));
                                setInputValue(inputValue.filter((value) => value !== v));
                            } }, v.label))),
                        searchable ? (react_1.default.createElement("input", { style: {
                                color: (0, varsUtilities_1.color)('content', 'default', 'primary'),
                                lineHeight: '24px',
                                background: 'transparent',
                                padding: 0,
                                border: 'none',
                                outline: 'none',
                                fontFamily: 'Inter',
                                fontSize: 14,
                            }, value: searchInput, placeholder: placeholder, onChange: (e) => {
                                setSearchInput(e.target.value);
                                setActiveIndex(0);
                            }, ref: textRef })) : (react_1.default.createElement(Text_1.Text, { selectable: "none", light: true }, placeholder)))),
                react_1.default.createElement("span", { style: {
                        pointerEvents: 'none',
                        position: 'absolute',
                        right: 12,
                        top: '50%',
                        transform: 'translateY(-50%)',
                    } },
                    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) => {
                        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',
                            minWidth: 'var(--radix-popover-trigger-width)',
                            maxHeight: 'min(300px, calc(var(--radix-popover-content-available-height) - 16px))',
                            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)',
                            ...ScrollArea_1.scrollAreaStyle,
                        } }, filteredOptions.length ? (filteredOptions.map((item, index) => (react_1.default.createElement(inlines_1.styled.div, { style: {
                            cursor: 'pointer',
                            background: index === activeIndex
                                ? (0, varsUtilities_1.color)('action', 'system', 'hover')
                                : 'transparent',
                            padding: '4px 12px 4px 42px',
                            [utils_1.BpTablet]: {
                                background: item.value === value
                                    ? (0, varsUtilities_1.color)('action', 'primary', 'subtleSelected')
                                    : 'transparent',
                            },
                            borderRadius: 8,
                            position: 'relative',
                            scrollMargin: '8px 0',
                        }, onClick: () => {
                            handleSelectItem(index);
                        }, onPointerMove: () => {
                            setActiveIndex(index);
                        }, key: item.value },
                        react_1.default.createElement(Text_1.Text, { color: "default", size: 14, weight: "medium" }, 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.MultiSelect = MultiSelect;
//# sourceMappingURL=MultiSelect.js.map