import { Button, Col, Collapse, Result, Row, Space } from "antd";
import React from "react";
import * as Sentry from "@sentry/electron/renderer";

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

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

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

  render() {
    if (this.state.hasErrored === true) {
      const errorItems = [
        {
          key: "error-details",
          label: "Error Details",
          children: (
            <>
              <div>
                <strong>{this.state.error.message}</strong>
              </div>
              <div>{this.state.error.stack}</div>
            </>
          )
        }
      ];

      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} items={errorItems} />
            </Col>
          </Row>
        </div>
      );
    } else {
      return this.props.children;
    }
  }
}
export default ErrorBoundary;
