import { Component } from "react";
import styles from "./ErrorBoundary.module.css";

export class ErrorBoundary extends Component {
  state = { error: null };

  static getDerivedStateFromError(error) {
    return { error };
  }

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

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

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

    return (
      <main className={styles.root}>
        <section className={styles.panel}>
          <h1 className={styles.title}>页面加载失败</h1>
          <p className={styles.message}>{this.state.error.message || "请刷新后重试"}</p>
          <div className={styles.actions}>
            <button className={styles.secondaryButton} type="button" onClick={this.reset}>
              返回页面
            </button>
            <button className={styles.primaryButton} type="button" onClick={this.reload}>
              刷新
            </button>
          </div>
        </section>
      </main>
    );
  }
}
