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

type Props = {
  resetKey: string;
  children: ReactNode;
};

type State = {
  error: string | null;
};

export class PreviewErrorBoundary extends Component<Props, State> {
  state: State = { error: null };

  static getDerivedStateFromError(error: Error): State {
    return {
      error: `${error.message}\n\n${error.stack ?? ''}`,
    };
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    console.error('[playground preview]', error, info);
    this.setState({
      error: `${error.message}\n\n${error.stack ?? ''}\n\n${info.componentStack ?? ''}`,
    });
  }

  componentDidUpdate(prevProps: Props) {
    if (prevProps.resetKey !== this.props.resetKey && this.state.error) {
      this.setState({ error: null });
    }
  }

  render() {
    if (this.state.error) {
      return <pre className="error-block">{this.state.error}</pre>;
    }
    return this.props.children;
  }
}
