import { __rest } from '../../_virtual/_tslib.js';
import React__default, { useState, useRef, useEffect } from 'react';
import CloseCircleFilled from '../../icons/CloseCircleFilled.js';
import { getId } from '../../utils/index.js';
import { Spinner } from '../Spinner/index.js';
import { SpinnerWrapper, IconWrapper, CloseButton } from './styles.js';
import { getChipVariant } from './utils.js';

function Chip(_a) {
    var { id, className, label, value, variant, icon, disabled = false, isLoading = false, selected = false, showClose = false, onClick, onRemove } = _a, props = __rest(_a, ["id", "className", "label", "value", "variant", "icon", "disabled", "isLoading", "selected", "showClose", "onClick", "onRemove"]);
    const ChipComponent = getChipVariant(variant);
    const [width, setWidth] = useState(0);
    const ref = useRef(null);
    useEffect(() => {
        if (ref.current)
            setWidth(ref.current.offsetWidth);
    }, [ref, variant, selected, label]);
    function handleCloseClick(event) {
        event.stopPropagation();
        if (!disabled && !isLoading && onRemove) {
            onRemove(value || label);
        }
        else {
            onClick(value || label);
        }
    }
    function handleClick() {
        if (selected && showClose)
            return;
        if (!isLoading && !disabled)
            onClick(value || label);
    }
    const appendTestId = getId(props['data-testid']);
    return (React__default.createElement(ChipComponent, { id: id || label, className: className || label, ref: ref, onClick: handleClick, disabled: disabled, selected: selected, showClose: showClose, isLoading: isLoading, "data-testid": appendTestId(), "data-trackid": props['data-trackid'], "aria-label": props['aria-label'] || label, "aria-selected": selected }, isLoading && !disabled ? (React__default.createElement(SpinnerWrapper, { width: width, selected: selected },
        React__default.createElement(Spinner, { size: "XS", variant: selected ? 'inverse' : 'secondary' }))) : (React__default.createElement(React__default.Fragment, null,
        icon && React__default.createElement(IconWrapper, null, icon),
        label,
        selected && showClose && (React__default.createElement(CloseButton, { "aria-label": "close-button", selected: selected, disabled: disabled, onClick: handleCloseClick, "data-testid": appendTestId('close-button') },
            React__default.createElement(CloseCircleFilled, null)))))));
}

export { Chip };
