import React, { Component, ReactNode } from 'react';

import ErrorComponent from '@/modules/@common/app/components/error';

interface ErrorBoundaryProps {
  children: ReactNode;
}

interface ErrorBoundaryState {
  hasError: boolean;
  error: Error | null;
}

class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error: Error) {
    return { hasError: true, error };
  }

  render() {
    if (this.state.hasError && this.state.error) {
      return process.env.NODE_ENV === 'production' ? <ErrorComponent /> : <div>{this.state.error.message}</div>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
