import React from "react";
import Button from "~/components/Button";
import { connect } from "react-redux";
import { publicApi } from "~/redux/actions";
import appConfig from "~/config";

const { version } = appConfig;
const agent = window.navigator.userAgent;
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { error: false };
  }
  static getDerivedStateFromError(error) {
    return { error };
  }
  render() {
    if (this.state.error) {
      let errors = this.state.error.stack.split("\n");
      if (errors[0].includes("dynamically imported")) {
        window.location.reload(true);
        return null;
      } // .filter((e) => !e.includes("node_module"));
      return (
        <div className="w-full h-full">
          <div className="border-error  bg-surface text-error rounded-lg border  flex-1 min-h-10 flex flex-col gap-2 p-3 m-3">
            <div className="font-6"> خطای نمایشی</div>
            <div className="ltr font-6">
              متاسفانه برای نمایش اطلاعات این صفحه خطایی وجود دارد
              {/* {errors[0].replace("ReferenceError:", "")} */}
            </div>
            {/* <hr />
            {errors.slice(1).map((e, i) => (
              <div key={i} className={"ltr text-xs"}>
                {e}
              </div>
            ))} */}
            <hr />
            <div className="flex flex-col md:flex-row-reverse gap-2 justify-start">
              <Button
                action={() =>
                  this.props.report({
                    error: this.state.error.stack,
                    version,
                    method: "UI",
                    path: window.location.pathname,
                    data: Object.fromEntries(
                      new URLSearchParams(window.location.search)
                    ),
                    statusCode: 600,
                    agent,
                    duration: 0,
                  })
                }
                text="گزارش خطا"
                primary
                className="bg-error  !my-0 px-2"
                loading={this.props.loading}
              />
              <Button
                // outline
                text="صفحه اصلی"
                link={"/"}
                className={"border border-error text-error !my-0 px-2"}
              />
            </div>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

export default connect(
  (state) => ({
    loading: state.publicApi.loading,
  }),
  { report: publicApi.report }
)(ErrorBoundary);
