import React from 'react';
import PropTypes from 'prop-types';
import Bugsnag from '@bugsnag/js';
import EmptyState from '../EmptyState';
import { useTrackRenderingFail, FAILURE_CAUSES } from '../hooks/useTrackRenderingFail';

const ErrorState = ({ chartName, channelType, message }) => {
  useTrackRenderingFail({
    chartName,
    failureCause: FAILURE_CAUSES.error,
    channelType,
  });

  return (<EmptyState
    header={message || 'So sorry! Something has gone a little wrong here'}
    description="If the problem persists, please contact us"
  />);
};

ErrorState.defaultProps = {
  chartName: '',
  channelType: '',
  message: null,
};

ErrorState.propTypes = {
  chartName: PropTypes.string,
  channelType: PropTypes.string,
  message: PropTypes.string,
};

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error) {
    Bugsnag.notify(error);
    this.setState({ hasError: true });
  }

  render() {
    if (this.state.hasError || this.props.hasError) {
      return (<ErrorState {...this?.props} />);
    }
    return this.props.children;
  }
}

ErrorBoundary.defaultProps = {
  children: null,
  hasError: false,
  message: null,
  chartName: '',
  channelType: '',
};

ErrorBoundary.propTypes = {
  children: PropTypes.node,
  hasError: PropTypes.bool,
  message: PropTypes.string,
  chartName: PropTypes.string,
  channelType: PropTypes.string,
};

export default ErrorBoundary;
