import { useEffect, useState } from "react";
import { parse } from "cookie";
import Modal from "../Modal";
import { fetchTtl } from "../../session";
import refreshSession from "../../session/refresh";
import logoutSession from "../../session/logout";

// calculate TWO_MINUTES for interval
const SECOND = 1000;
const MINUTE = 60 * SECOND;
const TWO_MINUTES = 2 * MINUTE;
const DEFAULT_SESSION_CHECK_INTERVAL = TWO_MINUTES;

// 120 seconds is 2 minutes
const DEFAULT_WARNING_TIMEOUT_SECONDS = 120;

function shouldShowInactiveDialog(
  timeRemainingSeconds,
  warningTimeoutSeconds = DEFAULT_WARNING_TIMEOUT_SECONDS,
) {
  return timeRemainingSeconds <= warningTimeoutSeconds;
}

const Session = () => {
  const [isOpen, setIsOpen] = useState(false);

  let ttlInterval;

  useEffect(() => {
    let didCancel = false;
    const cookies = parse(document.cookie);
    const hasAuthToken = !!cookies.qpp_auth_token;

    async function isSessionValid() {
      if (hasAuthToken) {
        const timeRemaining = await fetchTtl(cookies.qpp_auth_token);
        // safeguard against unmounted component
        if (didCancel) return;
        // token expired
        if (timeRemaining === 0) {
          logoutSession(window);
          return;
        }
        // token is about to expire
        if (shouldShowInactiveDialog(timeRemaining)) {
          setIsOpen(true);
        }
      }
    }

    ttlInterval = setInterval(isSessionValid, DEFAULT_SESSION_CHECK_INTERVAL);

    return () => {
      clearInterval(ttlInterval);
      didCancel = true;
    };
  }, []);

  // This Dialog shows up 2 minutes before the user session ends
  // giving the user an opportunity to refresh the token
  // or to sign out
  return (
    <Modal
      useDesignSystem
      title="You will be signed out within two minutes"
      isOpen={isOpen}
      primary={{
        title: "Keep me signed in",
        onClick: () => {
          refreshSession();
          clearInterval(ttlInterval);
          setIsOpen(false);
        },
      }}
      secondary={{
        title: "Sign me out now",
        onClick: () => logoutSession(window),
      }}
      onRequestClose={() => setIsOpen(false)}
    >
      <p>
        You have been inactive for thirty minutes. For your security, we will
        sign you out automatically.
      </p>
    </Modal>
  );
};

export default Session;
