import { Button, Col, Collapse, Result, Row, Space } from "antd";
import React from "react";

class ErrorBoundary extends React.Component {
  constructor() {
    super();
    this.state = {
      hasErrored: false,
      error: null,
      info: null,
    };
  }

  static getDerivedStateFromError(error) {
    console.log("ErrorBoundary -> getDerivedStateFromError -> error", error);
    return { hasErrored: true, error: error };
  }

  componentDidCatch(error, info) {
    console.log("Exception Caught by Error Boundary.", error, info);
    this.setState({ ...this.state, error, info });
  }

  render() {
    if (this.state.hasErrored === true) {
      return (
        <div>
          <Result
            status="500"
            title="Error!"
            subTitle="Error subtitle"
            extra={
              <Space>
                <Button
                  type="primary"
                  onClick={() => {
                    window.location.reload();
                  }}
                >
                  Refresh
                </Button>
              </Space>
            }
          />
          <Row>
            <Col offset={6} span={12}>
              <Collapse bordered={false}>
                <Collapse.Panel header="Error Details">
                  <div>
                    <strong>{this.state.error.message}</strong>
                  </div>
                  <div>{this.state.error.stack}</div>
                </Collapse.Panel>
              </Collapse>
            </Col>
          </Row>
        </div>
      );
    } else {
      return this.props.children;
    }
  }
}
export default ErrorBoundary;
