import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Snackbar from '@material-ui/core/Snackbar';

import notificationActions from '../redux/actions';

import Notification from './notification';

const mapStateToProps = state => ({
  notifications: state.notifications.toJSON()
});

const mapDispatchToProps = notificationActions;

@connect(mapStateToProps, mapDispatchToProps)
export default class Notifications extends Component {
  static propTypes = {
    notifications: PropTypes.arrayOf(
      PropTypes.shape({
        message: PropTypes.string.isRequired,
        variant: PropTypes.string.isRequired
      })
    ).isRequired,
    position: PropTypes.string
  }

  static defaultProps = {
    position: ''
  }

  render() {
    const { notifications, position } = this.props;

    const [ vertical, horizontal ] = position.split(' ');

    return (
      <Snackbar
        anchorOrigin={{
          horizontal: [ 'left', 'center', 'right' ].includes(horizontal) ? horizontal : 'right',
          vertical: [ 'top', 'bottom' ].includes(vertical) ? vertical : 'top'
        }}
        autoHideDuration={1000}
        open={notifications.length > 0}
      >
        <div>
          {notifications.map(({ key, ...rest }) => (
            <Notification
              key={key}
              $key={key}
              {...rest}
            />
          ))}
        </div>
      </Snackbar>
    );
  }
}
