var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
import React, { useContext, useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { prop } from 'ramda';
import { nanoid } from 'nanoid';
import Paper from '@mui/material/Paper';
import { PopupBoundariesContext } from '../contexts/PopupBoundariesContext';
import { Popper } from '../Popper';
import { useStyles } from './styles';
var DEFAULT_MAX_WIDTH = 521;
export var ReactSelectMenuWithPopper = function (props) {
    var _a = props.selectProps, inputRef = _a.inputRef, menuIsOpen = _a.menuIsOpen, inputValue = _a.inputValue, innerRef = props.innerRef, children = props.children, innerProps = props.innerProps;
    var _b = useState('id'), key = _b[0], setKey = _b[1];
    useEffect(function () {
        setKey(nanoid());
    }, [inputValue]);
    var styles = useStyles();
    var popupBoundariesContext = useContext(PopupBoundariesContext);
    var hasBoundariesElement = Boolean(popupBoundariesContext === null || popupBoundariesContext === void 0 ? void 0 : popupBoundariesContext.element);
    var boundariesWidth = hasBoundariesElement ? popupBoundariesContext.element.clientWidth : window.innerWidth;
    return (React.createElement(Popper, { anchorEl: inputRef.current, open: menuIsOpen, className: styles.popper, key: key, modifiers: [
            {
                name: 'preventOverflow',
                enabled: true,
                options: {
                    altAxis: true,
                    altBoundary: true,
                    tether: false,
                    boundary: hasBoundariesElement ? popupBoundariesContext.element : document.body,
                    padding: 5
                }
            }
        ], placement: "bottom-start" },
        React.createElement(Paper, __assign({ ref: innerRef, style: {
                minWidth: Math.min(prop('clientWidth', inputRef.current), boundariesWidth),
                maxWidth: Math.min(DEFAULT_MAX_WIDTH, boundariesWidth)
            } }, innerProps), children)));
};
ReactSelectMenuWithPopper.propTypes = {
    children: PropTypes.oneOfType([PropTypes.element, PropTypes.array]).isRequired,
    selectProps: PropTypes.shape({
        inputRef: PropTypes.object.isRequired,
        menuIsOpen: PropTypes.bool.isRequired,
        inputValue: PropTypes.string
    }).isRequired,
    innerRef: PropTypes.oneOfType([
        PropTypes.oneOf([null]),
        PropTypes.func,
        PropTypes.shape({
            current: PropTypes.any
        })
    ]).isRequired,
    innerProps: PropTypes.object.isRequired
};
