import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from "react";
import enhanceWithClickOutside from "react-click-outside";
import Icons from "../icons";
import { Indicator } from "../indicator";
import { Modal, Title, Wrapper } from "./styled";
class Dropdown extends React.Component {
    state = { selected: null, isModalOpened: false };
    componentDidMount() {
        this.selectFirst();
    }
    componentDidUpdate(prevProps) {
        const { children } = this.props;
        const prev = prevProps.children;
        if (children &&
            React.Children.count(children) > 0 &&
            prev &&
            React.Children.count(prev) > 0) {
            try {
                const keys = JSON.stringify(React.Children.toArray(children).map((el) => el.key));
                const prevKeys = JSON.stringify(React.Children.toArray(prev).map((el) => el.key));
                if (keys != prevKeys) {
                    this.selectFirst();
                }
            }
            catch (e) {
                if (e instanceof Error) {
                    console.error(e.message);
                }
            }
        }
    }
    selectFirst = () => {
        const { children } = this.props;
        if (React.Children.count(children) > 0) {
            const selected = React.Children.toArray(children)[0];
            this.setState({ selected });
        }
    };
    openModal = (e) => {
        e.preventDefault();
        e.stopPropagation();
        this.setState({ isModalOpened: !this.state.isModalOpened });
    };
    handleClickOutside() {
        this.setState({ isModalOpened: false });
    }
    wrapOnClick = () => {
        return React.Children.map(this.props.children, (child) => {
            return React.cloneElement(child, {
                onClick: (e) => {
                    this.setState({ selected: child, isModalOpened: false });
                    if (child.props.onClick) {
                        child.props.onClick(e);
                    }
                },
            });
        });
    };
    render() {
        const { theme, title } = this.props;
        return (_jsxs("div", { style: { zIndex: 100 }, children: [title && _jsx(Title, { theme: theme, children: title }), _jsxs(Wrapper, { className: "ui-dropdown__wrapper", theme: theme, onClick: this.openModal, children: [_jsx("div", { className: "ui-dropdown__selected", children: this.state.selected }), !this.props.disabled && (_jsx(Indicator, { opened: this.state.isModalOpened, width: "10", height: "9", viewBox: "0 0 10 9", fill: "none", xmlns: "http://www.w3.org/2000/svg", children: _jsx(Icons.Arrow, {}) })), !this.props.disabled && this.state.isModalOpened && (_jsx(Modal, { className: "ui-dropdown__modal", theme: this.props.theme, children: this.wrapOnClick() }))] })] }));
    }
}
export default enhanceWithClickOutside(Dropdown);
//# sourceMappingURL=index.js.map