"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.SelectPill = 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 ScrollArea_1 = require("../ScrollArea");
const utils_1 = require("../../utils");
const inputToString = (input) => {
    return typeof input === 'object'
        ? typeof input.label === 'string'
            ? input.label
            : input.value
        : '';
};
function SelectPill({ value, options, placeholder, prefix = 'Prefix', style, onChange, icon, }) {
    const [open, setOpen] = (0, react_1.useState)(false);
    // const [inputValue, setInputValue] = useState<PillOption | void>(() => {
    //   return options.find((e) => {
    //     e.value === value
    //   })
    // })
    const [inputValue, setInputValue] = (0, react_1.useState)(value);
    const inputRef = (0, react_1.useRef)(null);
    const [activeIndex, setActiveIndex] = (0, react_1.useState)(null);
    function handleSelectItem(index) {
        onChange(options[index].value);
        setInputValue(options[index]);
        setOpen(false);
        setActiveIndex(null);
    }
    function handleClose() {
        setOpen(false);
        setActiveIndex(null);
    }
    function handleOpen() {
        setOpen(true);
    }
    (0, react_1.useEffect)(() => {
        if (!value) {
            setInputValue(0);
        }
    }, [value]);
    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, { tabIndex: 0, onClick: () => {
                    handleOpen();
                }, onFocus: (e) => {
                    //TODO wont open for some reason?
                    handleOpen();
                }, value: inputValue ? inputToString(inputValue) : '', ref: inputRef, onChange: (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    console.log('sup:', e.target.value);
                    setInputValue({ value: 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);
                        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();
                        }
                    }
                }, style: {
                    display: 'flex',
                    boxSizing: 'border-box',
                    outline: 'none',
                    cursor: 'pointer',
                    minWidth: 130,
                    maxWidth: '100%',
                    padding: '4px 8px',
                    fontSize: 14,
                    lineHeight: '24px',
                    border: inputValue
                        ? `1px solid ${(0, varsUtilities_1.color)('inputBorder', 'neutralNormal')}`
                        : 'none',
                    background: inputValue
                        ? (0, varsUtilities_1.color)('background', 'default', 'strong')
                        : (0, varsUtilities_1.color)('action', 'neutral', 'subtleNormal'),
                    '&:hover': {
                        background: inputValue
                            ? (0, varsUtilities_1.color)('background', 'default', 'strong')
                            : (0, varsUtilities_1.color)('action', 'neutral', 'subtleHover'),
                        border: inputValue
                            ? `1px solid ${(0, varsUtilities_1.color)('inputBorder', 'neutralHover')}`
                            : 'none',
                    },
                    '&:active': {
                        background: inputValue
                            ? (0, varsUtilities_1.color)('background', 'default', 'strong')
                            : (0, varsUtilities_1.color)('action', 'neutral', 'subtleActive'),
                        border: inputValue
                            ? `1px solid ${(0, varsUtilities_1.color)('inputBorder', 'neutralActive')}`
                            : 'none',
                    },
                    borderRadius: 4,
                    gap: 8,
                    alignItems: 'center',
                    ...style,
                    '&:focus': {
                        backgroundColor: 'red',
                    },
                } },
                icon,
                react_1.default.createElement(inlines_1.styled.div, { style: { display: 'flex', gap: 6 } },
                    react_1.default.createElement(Text_1.Text, { selectable: "none", light: true },
                        prefix,
                        ":"),
                    react_1.default.createElement(Text_1.Text, { selectable: "none", style: { marginLeft: 6 } }, inputValue ? inputToString(inputValue) : placeholder)),
                inputValue ? (react_1.default.createElement(inlines_1.styled.div, { onClick: (e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        setInputValue(() => {
                            return options.find(() => '' === value);
                        });
                        setActiveIndex(0);
                        onChange(0);
                    }, style: {
                        marginLeft: 'auto',
                        width: '16px',
                        height: '16px',
                        borderRadius: '50%',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        '&:hover': {
                            backgroundColor: (0, varsUtilities_1.color)('action', 'neutral', 'subtleHover'),
                        },
                        // [BpTablet]: {
                        //   backgroundColor: 'transparent',
                        // },
                        '&:active': {
                            backgroundColor: (0, varsUtilities_1.color)('action', 'neutral', 'subtleActive'),
                        },
                    } },
                    react_1.default.createElement(icons_1.IconSmallClose, null))) : (react_1.default.createElement(icons_1.IconChevronDown, { style: { marginLeft: 'auto' } })))),
        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',
                            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)',
                            ...ScrollArea_1.scrollAreaStyle,
                        } }, options.length ? (options.map((item, index) => (react_1.default.createElement(inlines_1.styled.div, { id: `combobox-item-${index}`, style: {
                            cursor: 'pointer',
                            background: index === activeIndex
                                ? (0, varsUtilities_1.color)('action', 'system', 'hover')
                                : 'transparent',
                            [utils_1.BpTablet]: {
                                background: 'transparent',
                            },
                            padding: '4px 12px 4px 42px',
                            borderRadius: 8,
                            position: 'relative',
                            scrollMargin: '8px 0',
                        }, 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: "default" }))),
                        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, null)),
                        react_1.default.createElement(Text_1.Text, { color: "default", size: 14, weight: "medium" }, "No item found")))))))));
}
exports.SelectPill = SelectPill;
//# sourceMappingURL=Select.js.map