import * as React from 'react';
import * as classNames from 'classnames';
import {Children, PureComponent} from 'react';
import {Snackbar as ReactstrapSnackbar} from 'react-mdc-web';

const APP_MESSAGE: string = 'APP_MESSAGE';

const style = {
  hidden: {
    visibility: 'hidden',
  },
};

export interface SnackbarProps {
  open: boolean;
  children: string;
  onTimeout?: () => void;
}

export interface SnackbarState {
  open: boolean;
}

export class Snackbar extends PureComponent<SnackbarProps, SnackbarState> {
  state: SnackbarState;
  private initialRender: boolean = true;
  private snackbarElement: ReactstrapSnackbar;

  static defaultProps: Partial<SnackbarProps> = {
    onTimeout: () => { return; },
  };

  constructor(props: SnackbarProps) {
    super(props);

    this.state = {
      open: props.open,
    };
  }

  componentWillReceiveProps(nextProps: any) {
    if (nextProps.open !== this.props.open) {
      this.setState({open: nextProps.open});
    }
  }

  componentWillUpdate() {
    this.initialRender = false;
  }

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

    return (
      <ReactstrapSnackbar
        open={open}
        onTimeout={this.hide}
        ref={instance => this.snackbarElement = instance}
        className={classNames({'mdc-snackbar--hidden': this.initialRender})}
      >
        {this.props.children}
      </ReactstrapSnackbar>
    );
  }

  hide = () => {
    this.setState({open: false});
    this.props.onTimeout();
  }
}
