"use client";

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

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

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

  return (
    // @ts-ignore
    <Iframe
      id="zammad"
      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"
              ) 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);
              }
            });
          }
        }
      }}
    />
  );
};
