import { Component, type ReactNode } from "react";

type ErrorBoundaryProps = {
  children: ReactNode;
};

type ErrorBoundaryState = {
  error: Error | null;
};

export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  state: ErrorBoundaryState = { error: null };

  static getDerivedStateFromError(error: Error): ErrorBoundaryState {
    return { error };
  }

  componentDidCatch(error: Error, info: { componentStack?: string }): void {
    // Surface to the dev console; production telemetry would hook in here.
    // eslint-disable-next-line no-console
    console.error("[SIC] uncaught render error", error, info.componentStack);
  }

  private handleReload = () => {
    window.location.reload();
  };

  private handleReset = () => {
    this.setState({ error: null });
  };

  render() {
    const { error } = this.state;
    if (!error) return this.props.children;

    return (
      <div className="errorBoundary" role="alert">
        <div className="errorBoundaryCard">
          <strong className="panelHeading">{`Unrecoverable UI error`}</strong>
          <p>Something went wrong while rendering SIC. Your sessions and messages are still saved on the server.</p>
          <pre className="errorBoundaryMessage">{error.message}</pre>
          <div className="errorBoundaryActions">
            <button onClick={this.handleReset} type="button">
              {`Try again`}
            </button>
            <button className="primaryAction" onClick={this.handleReload} type="button">
              {`Reload page`}
            </button>
          </div>
        </div>
      </div>
    );
  }
}
