"use client";

import { FC, useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import Iframe from "react-iframe";
import { useSession } from "next-auth/react";
import { Box, Grid, CircularProgress } from "@mui/material";

type ZammadWrapperProps = {
  path: string;
  hideSidebar?: boolean;
};

export const ZammadWrapper: FC<ZammadWrapperProps> = ({
  path,
  hideSidebar = true,
}) => {
  const router = useRouter();
  const { data: session } = useSession({ required: true });
  const timeoutRef = useRef(null);
  const [hashCheckComplete, setHashCheckComplete] = useState(false);
  const [authenticated, setAuthenticated] = useState(false);
  const [display, setDisplay] = useState("none");
  const url = `/zammad${path}`;
  const id = url.replace(/[^a-zA-Z0-9]/g, "");

  useEffect(() => {
    const hash = window?.location?.hash;
    if (hash && hash.startsWith("#ticket/zoom/")) {
      const ticketID = hash.split("/").pop();
      router.push(`/tickets/${ticketID}`);
    }
    setHashCheckComplete(true);
  });

  useEffect(() => {
    if (!hashCheckComplete) return;

    const checkAuthenticated = async () => {
      const res = await fetch("/zammad/auth/sso", {
        method: "GET",
        redirect: "manual",
      });
      console.log({ res });
      if (res.type === "opaqueredirect") {
        setAuthenticated(true);
      } else {
        setAuthenticated(false);
      }
    };

    checkAuthenticated();
  }, [path, hashCheckComplete]);

  useEffect(() => {
    if (session === null) {
      timeoutRef.current = setTimeout(() => {
        if (session === null) {
          router.push("/login");
        }
      }, 3000);
    }

    if (session !== null) {
      clearTimeout(timeoutRef.current);
    }

    return () => clearTimeout(timeoutRef.current);
  }, [session]);

  if (!session || !authenticated) {
    console.log("Not authenticated");
    return (
      <Box sx={{ width: "100%" }}>
        <Grid
          container
          direction="column"
          sx={{ height: 500 }}
          justifyContent="center"
          alignContent="center"
          alignItems="center"
        >
          <Grid item>
            <CircularProgress size={80} color="success" />
          </Grid>
        </Grid>
      </Box>
    );
  }

  if (session && authenticated) {
    console.log("Session and authenticated");
    return (
      <Iframe
        id={id}
        url={url}
        width="100%"
        height="100%"
        frameBorder={0}
        styles={{ display }}
        onLoad={() => {
          const linkElement = document.querySelector(
            `#${id}`,
          ) as HTMLIFrameElement;

          console.log({ path });
          console.log({ id });
          console.log({ linkElement });
          if (
            linkElement.contentDocument &&
            linkElement.contentDocument?.querySelector &&
            linkElement.contentDocument.querySelector("#navigation") &&
            linkElement.contentDocument.querySelector("body")
          ) {
            // @ts-ignore
            linkElement.contentDocument.querySelector("#navigation").style =
              "display: none";
            // @ts-ignore
            linkElement.contentDocument.querySelector("body").style =
              "font-family: Arial";

            if (
              hideSidebar &&
              linkElement.contentDocument.querySelector(".sidebar")
            ) {
              // @ts-ignore
              linkElement.contentDocument.querySelector(".sidebar").style =
                "display: none";
            }

            // @ts-ignore
            if (linkElement.contentDocument.querySelector(".overview-header")) {
              // @ts-ignore
              (
                linkElement.contentDocument.querySelector(
                  ".overview-header",
                ) as any
              ).style = "display: none";
            }

            setDisplay("inherit");

            if (linkElement.contentWindow) {
              linkElement.contentWindow.addEventListener("hashchange", () => {
                const hash = linkElement.contentWindow?.location?.hash ?? "";
                if (hash.startsWith("#ticket/zoom/")) {
                  setDisplay("none");
                  const ticketID = hash.split("/").pop();
                  router.push(`/tickets/${ticketID}`);
                  setTimeout(() => {
                    setDisplay("inherit");
                  }, 1000);
                }
              });
            }
          }
        }}
      />
    );
  }
};
