import Policy from "../Policy";
import { useTranslation } from "react-i18next";
import styles from "./styles.module.css";
import AppleAuthButton from "./AppleAuthButton";
import routes from "@/routes";
import Title from "../Title";
import { APNG } from "apng-js";
import Player from "apng-js/types/library/player";
import { useEffect, useRef } from "react";
import GoogleAuthButton from "./GoogleAuthButton";

let apngPlayer: Player | null = null;

interface AuthPageProps {
  padLockApng: Error | APNG;
}

function AuthPage({ padLockApng }: AuthPageProps): JSX.Element {
  const { t } = useTranslation();
  const padLockCanvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    let padLockTimeOut: NodeJS.Timeout;
    async function getApngPlayer() {
      const context = padLockCanvasRef.current?.getContext("2d");
      if (context && !(padLockApng instanceof Error)) {
        context.canvas.height = padLockApng.height;
        context.canvas.width = padLockApng.width;
        const _apngPlayer = await padLockApng.getPlayer(context);
        apngPlayer = _apngPlayer;
        if (apngPlayer) {
          apngPlayer.play();
          padLockTimeOut = setTimeout(() => {
            if (apngPlayer) {
              apngPlayer.pause();
            }
          }, 900);
        }
      }
    }
    getApngPlayer();
    return () => {
      clearTimeout(padLockTimeOut);
    };
  }, [padLockApng]);

  const handleAppleAuth = async () => {
    window.location.href = routes.server.appleAuth(
      encodeURI(`${window.location.origin}/auth/result/`)
    );
  };

  const handleGoogleAuth = async () => {
    window.location.href = routes.server.googleAuth(
      encodeURI(`${window.location.origin}/auth/result/`)
    );
  };

  return (
    <section className={`${styles.page} page`}>
      <Title variant="h2" className={styles.title}>
        Sign in to save your energy analysis, horoscope, and predictions.
      </Title>
      <canvas className={styles["pad-lock"]} ref={padLockCanvasRef} />
      <p className={styles.disclaimer}>{t("we_dont_share")}</p>
      <div className={styles["buttons-container"]}>
        <GoogleAuthButton onClick={handleGoogleAuth} />
        <AppleAuthButton onClick={handleAppleAuth} />
      </div>
      <Policy className={styles.policy} sizing="medium">
        {t("_continue_agree", {
          eulaLink: (
            <a
              href="https://aura.wit.life/terms"
              target="_blank"
              rel="noopener noreferrer"
            >
              {t("eula")}
            </a>
          ),
          privacyLink: (
            <a
              href="https://aura.wit.life/privacy"
              target="_blank"
              rel="noopener noreferrer"
            >
              {t("privacy_policy")}
            </a>
          ),
        })}
      </Policy>
    </section>
  );
}

export default AuthPage;
