import React, { Component } from 'react';
import { Snackbar } from '@material-ui/core';
import Alert from './Alert';
import Constant from './Constant';

class AlertSnackbar extends Component {
  state = {
    open: false,
    message: '',
    severity: Constant.ALERT_SEVIRITY.SUCCESS,
  };

  componentDidMount() {
    const { open, message, severity } = this.props;
    if (open !== undefined) {
      this.setState({ open });
    }
    if (message) {
      this.setState({ message });
    }
    if (severity) {
      this.setState({ severity });
    }
  }

  componentDidUpdate(prevProps) {
    const { open, message, severity } = this.props;
    
    if (prevProps.open !== open && open !== undefined) {
      this.setState({ open });
    }
    
    if (prevProps.message !== message && message) {
      this.setState({ message, open: true });
    }
    
    if (prevProps.severity !== severity) {
      this.setState({ severity });
    }
  }

  handleClose = (event, reason) => {
    const { onClose, disableClickawayClose = false } = this.props;
    
    if (disableClickawayClose && reason === 'clickaway') {
      return;
    }
    
    this.setState({ open: false });
    
    if (onClose) {
      onClose(event, reason);
    }
  };

  render() {
    const {
      // Props untuk custom content
      children,
      
      // Props untuk Snackbar
      autoHideDuration = 2000,
      anchorOrigin = { vertical: 'bottom', horizontal: 'center' },
      
      // Props untuk Alert
      action,
      icon,
      onClose: propOnClose,
      
      // Lainnya
      ...snackbarProps
    } = this.props;

    const { open, message, severity } = this.state;

    return (
      <Snackbar
        open={open}
        autoHideDuration={autoHideDuration}
        onClose={this.handleClose}
        anchorOrigin={anchorOrigin}
        {...snackbarProps}
      >
        <Alert 
          onClose={this.handleClose} 
          severity={severity}
          action={action}
          icon={icon}
        >
          {children || message}
        </Alert>
      </Snackbar>
    );
  }
}

export default AlertSnackbar;