import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import { ActionTypes } from 'constants/Common';
import StoreMixin from 'lib/StoreMixin';
import NotificationStore from 'stores/Notifications';
import dispatcher from 'dispatcher';

import { i18n } from 'lib/i18n';

import FlatButton from 'ui/FlatButton';
import Icon from 'ui/Icon';

import './index.css';
import './animation.css';

const Notifications = React.createClass({

    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        return { notifications: NotificationStore.getState() };
    },

    componentDidMount() {
        this.subscribe(NotificationStore);
    },

    _renderNotification(notification, index) {
        const { key, type, message, options = {} } = notification;
        let actions;

        if (!message) {
            return null;
        }

        const handleClick = () => {
            dispatcher.dispatch(ActionTypes.REMOVE_NOTIFICATION, { key });

            if (options.onClose) {
                options.onClose();
            }
        };

        const className = [
            'notification',
            type ? `notification__${type}` : null,
        ].filter(Boolean).join(' ');

        if (options.onCancel) {
            actions = (
                <div className="notification-actions">
                    <span onClick={options.onCancel}>{i18n('common.action.cancel')}</span>
                </div>
            );
        }

        return (
            <div
                className={className}
                key={index}
            >
                <div
                    className="notification-content"
                    role="status"
                >
                    {message}
                    {type === 'error' && (
                        <div className="notification-meta">
                            {`${window.ya.connect.initial.requestId} ${new Date().toISOString()}`}
                        </div>
                    )}
                </div>
                {actions}
                <FlatButton
                    className="close"
                    onClick={handleClick}
                    ariaLabel={i18n('common.action.close')}
                >
                    <Icon type="light-cross" />
                </FlatButton>
            </div>
        );
    },

    render() {
        const { notifications } = this.state;

        if (!notifications.size) {
            return null;
        }

        return (
            <div className="notifications">
                {notifications.toArray().map(this._renderNotification)}
            </div>
        );
    },

});

export default Notifications;
