import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {observer} from 'mobx-react/index';
import isString from 'lodash.isstring';
import classNames from 'classnames';
import Button from '../Button';
import Icon from '../Icon';
import Translate from '../Translate';
import {action, observable} from 'mobx';
import './styles.scss';

const PopupFooter = ({buttons, footerContent, clickButtonHandler}) => {
    return (Boolean(buttons.length) || (isString(footerContent) ? Boolean(footerContent.length) : true))
        && (
            <div className="Popup__footer">
                {buttons.map((button) => (
                    <Button
                        isPrimary={button.isPrimary}
                        isSecondary={button.isSecondary}
                        isAdvanced={button.isAdvanced}
                        key={Math.random()}
                        title={button.title}
                        isDisabled={button.isDisabled || false}
                        elementId={`popup-footer-button-${button.title.replace(/\s[A-Za-z]/g, '_')}`}
                        onChangePromise={clickButtonHandler(button)}
                    />
                ))}
                {footerContent}
            </div>
        );
};

PopupFooter.propTypes = {
    buttons: PropTypes.array.isRequired,
    clickButtonHandler: PropTypes.func.isRequired,
    footerContent: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.element,
    ]).isRequired,
};

const PopupHeader = ({title, clickCloseHandler}) => {
    return (
        <div className="Popup__header">
            <Translate tag={title} />
            <button
                className="Popup__header-close-button"
                onClick={clickCloseHandler}
            >
                <Icon
                    name="close"
                    color="gray-dark"
                    size="small"
                />
            </button>
        </div>
    );
};

PopupHeader.propTypes = {
    title: PropTypes.string.isRequired,
    clickCloseHandler: PropTypes.func.isRequired,
};

@observer
class Popup extends Component {
    @observable isPopupOpen = false;

    constructor(props) {
        super();
        this.popup = null;

        if (props.isVisible) {
            this.isPopupOpen = true;
        }

        this.clickCloseHandler = this.clickCloseHandler.bind(this);
        this.clickButtonHandler = this.clickButtonHandler.bind(this);
    }

    clickCloseHandler() {
        return this.props.closePromise()
            .then(() => {
                this.isPopupOpen = false;
                return this.isPopupOpen;
            });
    }

    clickButtonHandler(button) {
        return () => button.promise()
            .then(() => {
                if (!button.preventClose) {
                    this.isPopupOpen = false;
                }

                return this.isPopupOpen;
            });
    }

    @action
    openPopup() {
        this.isPopupOpen = true;
    }

    componentWillReceiveProps(props) {
        this.isPopupOpen = props.isVisible;
    }

    render() {
        if (!this.isPopupOpen) {
            return null;
        }

        const overlayClasses = classNames('PopupOverlay', {
            PopupOverlay_black: this.props.isBlackOverlay,
        });

        setTimeout(() => {
            if (this.popup) {
                this.popup.classList.add('Popup_active');
            }
        }, 30);

        const popupContentClass = classNames('Popup__content', {
            Popup__content_overflow: this.props.isOverflow,
        });

        return (
            <div className="PopupWrapper">
                <div className="PopupInner">
                    <div
                        role="presentation"
                        className={overlayClasses}
                        onClick={this.clickCloseHandler}
                    />
                    <div
                        ref={(node) => { this.popup = node; }}
                        className="Popup"
                    >
                        <PopupHeader
                            title={this.props.title}
                            closePromise={this.props.closePromise}
                            clickCloseHandler={this.clickCloseHandler}
                        />
                        <div className={popupContentClass}>
                            {this.props.content}
                        </div>
                        <PopupFooter
                            buttons={this.props.buttons}
                            footerContent={this.props.footerContent}
                            clickButtonHandler={this.clickButtonHandler}
                        />
                    </div>
                </div>
            </div>
        );
    }
}

Popup.propTypes = {
    title: PropTypes.string,
    content: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.element,
    ]),
    isBlackOverlay: PropTypes.bool,
    isVisible: PropTypes.bool,
    isOverflow: PropTypes.bool,
    buttons: PropTypes.array,
    closePromise: PropTypes.func,
    footerContent: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.element,
    ]),
};

Popup.defaultProps = {
    title: 'Popup',
    content: 'Content',
    isBlackOverlay: false,
    isVisible: false,
    isOverflow: false,
    buttons: [
        {
            title: 'Ok',
            isAdvanced: false,
            isPrimary: true,
            isSecondary: false,
            preventClose: false,
            promise: () => Promise.resolve(),
        },
    ],
    footerContent: '',
    closePromise: () => Promise.resolve(),
};

export default Popup;
