import { Button, Typography } from "@mui/material";
// import { LottiePlayer } from "lottie-react";
import { PropTypes } from "prop-types";
import { Grid } from "../grid/Grid";
import groovyWalkAnimation from "../../assets/lottie/error.json";
import Lottie from "lottie-react";
import useUserProfile from "../../features/authentication/hooks/useUserProfile";
import { useEffect } from "react";

export function ErrorFallback({ error, resetErrorBoundary }) {
  useEffect(() => {
    const body = document.body;
    body.style.background = "#341f97";

    return () => {
      body.style.background = "";
    };
  }, []);

  const nVer = navigator.appVersion;
  const nAgt = navigator.userAgent;
  let browserName = navigator.appName;
  let fullVersion = "" + parseFloat(navigator.appVersion);
  let majorVersion = parseInt(navigator.appVersion, 10);
  let nameOffset, verOffset, ix;

  // In Opera, the true version is after "OPR" or after "Version"
  if ((verOffset = nAgt.indexOf("OPR")) !== -1) {
    browserName = "Opera";
    fullVersion = nAgt.substring(verOffset + 4);
    if ((verOffset = nAgt.indexOf("Version")) !== -1)
      fullVersion = nAgt.substring(verOffset + 8);
  }
  // In MS Edge, the true version is after "Edg" in userAgent
  else if ((verOffset = nAgt.indexOf("Edg")) !== -1) {
    browserName = "Microsoft Edge";
    fullVersion = nAgt.substring(verOffset + 4);
  }
  // In MSIE, the true version is after "MSIE" in userAgent
  else if ((verOffset = nAgt.indexOf("MSIE")) !== -1) {
    browserName = "Microsoft Internet Explorer";
    fullVersion = nAgt.substring(verOffset + 5);
  }
  // In Chrome, the true version is after "Chrome"
  else if ((verOffset = nAgt.indexOf("Chrome")) !== -1) {
    browserName = "Chrome";
    fullVersion = nAgt.substring(verOffset + 7);
  }
  // In Safari, the true version is after "Safari" or after "Version"
  else if ((verOffset = nAgt.indexOf("Safari")) !== -1) {
    browserName = "Safari";
    fullVersion = nAgt.substring(verOffset + 7);
    if ((verOffset = nAgt.indexOf("Version")) !== -1)
      fullVersion = nAgt.substring(verOffset + 8);
  }
  // In Firefox, the true version is after "Firefox"
  else if ((verOffset = nAgt.indexOf("Firefox")) !== -1) {
    browserName = "Firefox";
    fullVersion = nAgt.substring(verOffset + 8);
  }
  // In most other browsers, "name/version" is at the end of userAgent
  else if (
    (nameOffset = nAgt.lastIndexOf(" ") + 1) <
    (verOffset = nAgt.lastIndexOf("/"))
  ) {
    browserName = nAgt.substring(nameOffset, verOffset);
    fullVersion = nAgt.substring(verOffset + 1);
    if (browserName.toLowerCase() === browserName.toUpperCase()) {
      browserName = navigator.appName;
    }
  }
  // trim the fullVersion string at semicolon/space if present
  if ((ix = fullVersion.indexOf(";")) !== -1)
    fullVersion = fullVersion.substring(0, ix);
  if ((ix = fullVersion.indexOf(" ")) !== -1)
    fullVersion = fullVersion.substring(0, ix);

  majorVersion = parseInt("" + fullVersion, 10);
  if (isNaN(majorVersion)) {
    fullVersion = "" + parseFloat(navigator.appVersion);
    majorVersion = parseInt(navigator.appVersion, 10);
  }

  let OSName = "Unknown OS";
  if (navigator.appVersion.indexOf("Win") !== -1) OSName = "Windows";
  if (navigator.appVersion.indexOf("Mac") !== -1) OSName = "MacOS";
  if (navigator.appVersion.indexOf("X11") !== -1) OSName = "UNIX";
  if (navigator.appVersion.indexOf("Linux") !== -1) OSName = "Linux";

  const [, userProfile] = useUserProfile();

  const reportObj = {
    error: {
      stack: error?.stack || "No stack trace available",
      msg: error?.message || "Unknown error",
    },
    url: window.location?.href || window.location,
    userProfile: userProfile || null,
    date: new Date(),
    os: OSName,
    browserName,
    browserVersion: fullVersion + "-" + majorVersion,
    navigatorAppName: navigator.appName,
    navigatorAppVersion: nVer,
    navigatorUserAgent: nAgt,
  };

  useEffect(() => {
    console.log(
      { error, reportObj },
      JSON.stringify(error, null, 2),
      "Current Error"
    );
  }, [error]);
  useEffect(() => {
    if (error) {
      // if (window.location.hostname !== "localhost") {
      //   fetch("https://core-inventory.iran.liara.run/crashes/rasadyar/", {
      //     method: "POST", // or 'PUT'
      //     headers: {
      //       "Content-Type": "application/json",
      //     },
      //     body: JSON.stringify(reportObj),
      //   })
      //     .then((response) => response.json())
      //     .then((data) => {
      //     })
      //     .catch((error) => {
      //       console.error("Error:", error);
      //     });
      // }
    }
  }, [error]);

  return (
    <Grid
      container
      sx={{
        backgroundColor: "#341f97",
        alignItems: "center",
        justifyContent: "center",
        minHeight: "100vh",
        width: "100%",
        position: "fixed",
        top: 0,
        left: 0,
        zIndex: 9999,
      }}
    >
      <Grid
        display="flex"
        flexDirection="column"
        xs={8}
        gap={2}
        justifyContent="center"
      >
        <Grid width="300px" alignSelf="center">
          {groovyWalkAnimation ? (
            <Lottie animationData={groovyWalkAnimation} loop={true} />
          ) : (
            <Typography variant="h3" color="white">
              ⚠️
            </Typography>
          )}
        </Grid>
        <Grid>
          <Typography variant="h5" color="#DC6E56">
            متاسفیم، این بخش در دست توسعه است!
          </Typography>
        </Grid>
        <Grid>
          <Typography variant="body1" color="white">
            مشکل شما به بخش فنی گزارش داده شد و در حال رفع مشکل هستیم، لطفا چند
            لحظه دیگر تلاش کنید.
          </Typography>
        </Grid>
        <Grid>
          <Typography variant="body1" color="white">
            در صورت رفع نشدن مشکل با شماره 02128421237 تماس حاصل فرمایید.
          </Typography>
        </Grid>

        <Grid mt={2}>
          <Button
            variant="contained"
            onClick={resetErrorBoundary}
            color="primary"
          >
            تلاش دوباره
          </Button>
        </Grid>
      </Grid>
    </Grid>
  );
}

ErrorFallback.propTypes = {
  error: PropTypes.any,
  resetErrorBoundary: PropTypes.any,
};
