import { FC, useState } from "react";
import { useRouter } from "next/router";
import Iframe from "react-iframe";

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

export const InternalZammadWrapper: FC<InternalZammadWrapperProps> = ({
  path,
  hideSidebar = true,
}) => {
  const router = useRouter();
  const [display, setDisplay] = useState("none");
  const url = `${origin}/zammad${path}`;
  console.log({ origin, path, url });

  return (
    // @ts-ignore
    <Iframe
      id="link"
      url={url}
      width="100%"
      height="100%"
      frameBorder={0}
      styles={{ display }}
      onLoad={() => {
        const linkElement = document.querySelector("iframe");
        if (
          linkElement.contentDocument &&
          linkElement.contentDocument?.querySelector &&
          linkElement.contentDocument.querySelector("#navigation") &&
          linkElement.contentDocument.querySelector("body") &&
          linkElement.contentDocument.querySelector(".sidebar")
        ) {
          // @ts-ignore
          linkElement.contentDocument.querySelector("#navigation").style =
            "display: none";
          // @ts-ignore
          linkElement.contentDocument.querySelector("body").style =
            "font-family: Arial";

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

          // @ts-ignore
          if (linkElement.contentDocument.querySelector(".overview-header")) {
            // @ts-ignore
            linkElement.contentDocument.querySelector(".overview-header").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);
              }
            });
          }
        }
      }}
    />
  );
};
