import { Component, type ErrorInfo, type ReactNode } from 'react';
import ErrorMessage from '../components/ErrorMessage.js';

interface Props {
  children: ReactNode;
  onReset?: () => void;
}

interface State {
  hasError: boolean;
  error?: Error;
  errorInfo?: ErrorInfo;
}

class ErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false };
  }

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

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    console.error('Error caught by boundary:', {
      error,
      componentStack: errorInfo.componentStack,
    });

    this.setState({ errorInfo });
  }

  resetError = () => {
    this.setState({ hasError: false });
    this.props.onReset?.();
  };

  render() {
    if (this.state.hasError) {
      return (
        <div className="conductor">
          <ErrorMessage>
            Sorry, something went wrong.{' '}
            <button onClick={this.resetError}>Please reload the app.</button>
          </ErrorMessage>
        </div>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
