import makeStyles from "@mui/styles/makeStyles";
import { FC, Fragment, useEffect, useRef } from "react";
import { useAuth } from "./auth.provider";
const useStyles = makeStyles((theme) => {
  debugger;
  return {
    iframe: {
      height: "300px",
      width: "500px",
      position: "absolute",
      top: "100px",
      left: "50%",
      transform: "translateX(-50%)",
      zIndex: theme.zIndex.modal,
      border: "none",
      boxShadow: theme.shadows[4],
    },
    mask: {
      top: "0",
      left: "0",
      bottom: "0",
      right: "0",
      position: "absolute",
      backgroundColor: "rgba(0, 0, 0, 0.3)",
      zIndex: theme.zIndex.modal,
    },
  };
});

export const Login: FC = () => {
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const { login } = useAuth();
  useEffect(() => {
    const iframe = iframeRef.current;
    if (!iframe) {
      return;
    }
    let messagePort: MessagePort;
    const onLoad = (ev: MessageEvent) => {
      if (ev.data !== "init-channel") {
        return;
      }
      messagePort = ev.ports?.[0] as MessagePort;
      messagePort.onmessage = (ev: MessageEvent) => {
        if (ev.data?.type === "logged") {
          login(ev.data.payload);
        }
      };
    };
    window.addEventListener("message", onLoad);

    return () => {
      window.removeEventListener("message", onLoad);
    };
  }, [login]);

  const classes = useStyles();
  return (
    <Fragment>
      <div className={classes.mask} />
      <iframe
        ref={iframeRef}
        className={classes.iframe}
        title="Auth"
        src="https://user.rpi.ivanli.cc/auth/login"
      ></iframe>
    </Fragment>
  );
};
