import React, { useEffect, useState } from "react";
import { config } from "../config";

/**
 * This is based on Rodney Urquhart's example https://github.com/RodneyU215
 * https://github.com/Webflow-Examples/Apps-v2-Hybrid-Auth-Demo/tree/main#key-components
 * https://www.loom.com/share/28afbb72a30e42ca9333a77e65fbd025
 *
 * tl;dr app.nocodelytics.com/webflow_auth.html will post the token with
 * `window.parent.postMessage(token, extensionURL)`
 *
 * This component listens to that event and save the token in local storage
 */

export interface AuthIFrameProps {
  onReady: () => void;
}

export const AuthIFrame: React.FC<AuthIFrameProps> = (props) => {
  const [showIFrame, setShowIframe] = useState<boolean>(true);

  const setToken = (token: string): boolean => {
    if (!token) {
      return false;
    }
    localStorage.setItem(config.localstorageKeys.token, token);
    props.onReady();
    setShowIframe(false);
    return true;
  };

  const handleMessage = (event: MessageEvent) => {
    window.removeEventListener("message", handleMessage);
    if (event.origin.startsWith(config.baseUrl)) {
      setToken(event.data);
      console.info(
        `new token received from ${config.authIFrameUrl}`,
        event.data
      );
    } else {
      console.error(`wrong origin ${event.origin} !== ${config.baseUrl}`);
      return;
    }
  };

  useEffect(() => {
    window.addEventListener("message", handleMessage);
    return () => {
      window.removeEventListener("message", handleMessage);
    };
  }, []);

  return (
    <iframe
      style={{ display: showIFrame ? "block" : "none" }}
      src={config.authIFrameUrl}
    />
  );
};
