import { parse as queryParse, stringify as queryStringify } from "query-string";
import Url from "url-parse";
import Debug from "debug";
import { useEffect, useMemo, useState } from "react";
import {
  ElementComponent,
  ElementProps,
  ElementTypeName,
  ShowHideDefaultVisibility,
  WebpageElementData,
} from "./types";
import useBaseElementStyles from "./hooks/useBaseElementStyles";
import useEditableFeatures from "./hooks/useEditableFeatures";

const debug = Debug("Webpage element");

function Webpage(props: ElementProps<WebpageElementData>) {
  const { resizeHandles, moveListeners, currentDimensions } =
    useEditableFeatures(props);
  const { baseClasses, baseStyles } = useBaseElementStyles(
    currentDimensions,
    props.scaleFactor,
    props.isEditable,
  );

  const [hasLoaded, setHasLoaded] = useState<boolean>(false);

  const {
    scale,
    source: userSource,
    allowFullscreen,
    allowScrolling,
    allowNavigation,
    allowPopup,
    name,
  } = props.element;
  const { element, saveElement, isEditable } = props;

  // extract URL if the user pasted in a <iframe ...>
  const source = useMemo(() => {
    let intendedUrl = userSource;

    if (userSource.startsWith("<")) {
      const tmp = document.createElement("div");
      tmp.innerHTML = userSource;
      intendedUrl = tmp.querySelector("iframe")?.src ?? userSource;
    }

    const url = new Url(intendedUrl, false);

    if (url.hostname === "player.twitch.tv") {
      debug("Detected Twitch URL, setting parent");

      const query = queryParse(url.href.substring(url.href.indexOf("?")));
      if (query.parent !== new Url(window.location.href).hostname) {
        query.parent = new Url(window.location.href).hostname;

        url.set("query", queryStringify(query));

        intendedUrl = url.toString();
      }
    }

    // update URL to be proper
    if (isEditable && intendedUrl !== userSource) {
      saveElement({ ...element, source: intendedUrl });
    }

    return intendedUrl;
  }, [userSource, element, saveElement, isEditable]);

  useEffect(() => {
    setHasLoaded(false);
  }, [source]);

  const userScaleFactor = (props.scaleFactor * scale) / 100;

  return (
    <div
      className={baseClasses}
      style={{
        ...baseStyles,
      }}
      {...moveListeners}
    >
      <iframe
        style={{
          position: "absolute",
          overflow: allowScrolling ? "auto" : "hidden",
          width: `calc(100% * ${1 / userScaleFactor})`,
          height: `calc(100% * ${1 / userScaleFactor})`,
          transform: `scale(${userScaleFactor})`,
          transformOrigin: "0 0",
        }}
        frameBorder={0}
        title={name}
        allow={[
          "autoplay",
          "geolocation",
          "camera",
          "microphone",
          ...(allowFullscreen ? ["fullscreen"] : []),
        ]
          .map((a) => `${a} *`)
          .join(";")}
        scrolling={allowScrolling ? "auto" : "no"}
        sandbox={[
          "allow-scripts",
          "allow-forms",
          "allow-same-origin",
          ...(allowPopup
            ? ["allow-popups", "allow-modals", "allow-popups-to-escape-sandbox"]
            : []),
          ...(allowFullscreen ? ["allow-presentation"] : []),
        ].join(" ")}
        src={source}
        onLoad={(e) => {
          if (hasLoaded) {
            if (!allowNavigation) {
              debug("Load detected! Going back...");
              setHasLoaded(false);
              (e.target as HTMLIFrameElement).src = source;
            }
          } else {
            setHasLoaded(true);
          }
        }}
      />
      {resizeHandles}
    </div>
  );
}

const WebpageForExport =
  Webpage as unknown as ElementComponent<WebpageElementData>;

WebpageForExport.elementName = "Web Page";
WebpageForExport.description =
  "An element which embeds a remote website into the presentation.";
WebpageForExport.icon = "web";
WebpageForExport.blankFactory = (newId, newZ, data) => ({
  type: ElementTypeName.Webpage,
  name: "New Web Page",

  id: newId,
  x: data.metadata.width / 2 - 150,
  y: data.metadata.height / 2 - 50,
  z: newZ,

  isLocked: false,
  width: 300,
  height: 100,

  source: "https://example.com/",
  allowFullscreen: true,
  allowScrolling: true,
  allowNavigation: true,
  allowPopup: true,
  scale: 100,

  visible: {
    default: ShowHideDefaultVisibility.Show,
    except: [],
  },
});
WebpageForExport.clone = (source, newId, newName, newZ) => ({
  type: ElementTypeName.Webpage,
  name: newName,

  id: newId,
  x: source.x,
  y: source.y,
  z: newZ,

  isLocked: source.isLocked,
  width: source.width,
  height: source.height,

  source: source.source,
  allowFullscreen: source.allowFullscreen,
  allowScrolling: source.allowScrolling,
  allowNavigation: source.allowNavigation,
  allowPopup: source.allowPopup,
  scale: source.scale,

  visible: source.visible,
});

export default WebpageForExport;
