import React from 'react'
import PropTypes from 'prop-types'

export class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props)
    this.state = { error: null, errorInfo: null }
  }

  componentDidCatch(error, errorInfo) {
    // Catch errors in any components below and re-render with error message
    this.setState({
      error: error,
      errorInfo: errorInfo
    })
    // You can also log error messages to an error reporting service here
  }

  render() {
    if (this.state.errorInfo) {
      if (this.props.errorComponent) {
        return React.cloneElement(this.props.errorComponent, { ...this.state })
      }
      // Error path
      return (
        <div>
          <h2>Something went wrong.</h2>
          <details style={{ whiteSpace: 'pre-wrap' }}>
            {this.state.error && this.state.error.toString()}
            <br />
            {this.state.errorInfo.componentStack}
          </details>
        </div>
      )
    }
    // Normally, just render children
    return this.props.children
  }
}

ErrorBoundary.propTypes = {
  children: PropTypes.element,
  errorComponent: PropTypes.element
}

export function withErrorBoundary(errorComponent) {
  return (WrappedComponent) => (props) => {
    return (
      <ErrorBoundary errorComponent={errorComponent}>
        <WrappedComponent {...props} />
      </ErrorBoundary>
    )
  }
}
