import React, { useCallback, useEffect, useState } from "react";

type RedirectPageProps = {
  enableRedirectNowButton: boolean;
};

const REDIRECT_DELAY_MS = 10000;
const TARGET_URL = "https://hypershelf.demo.stf";

export function RedirectPage({
  enableRedirectNowButton
}: RedirectPageProps): JSX.Element {
  const [remainingMs, setRemainingMs] = useState<number>(REDIRECT_DELAY_MS);

  useEffect(() => {
    const redirectTimeoutId = window.setTimeout(() => {
      window.location.assign(TARGET_URL);
    }, REDIRECT_DELAY_MS);

    const intervalId = window.setInterval(() => {
      setRemainingMs(previous => {
        const next = previous - 1000;
        if (next <= 0) {
          window.clearInterval(intervalId);
          return 0;
        }
        return next;
      });
    }, 1000);

    return () => {
      window.clearTimeout(redirectTimeoutId);
      window.clearInterval(intervalId);
    };
  }, []);

  const handleRedirectNow = useCallback((): void => {
    window.location.assign(TARGET_URL);
  }, []);

  const secondsRemaining = Math.ceil(remainingMs / 1000);

  return (
    <main
      style={{
        minHeight: "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "#ffffff",
        color: "#000000",
        fontFamily: "system-ui, -apple-system, BlinkMacSystemFont, sans-serif"
      }}
    >
      <div style={{ textAlign: "center" }}>
        <h1 style={{ fontSize: "1.5rem", marginBottom: "0.5rem" }}>
          Hello
        </h1>
        <p style={{ marginBottom: enableRedirectNowButton ? "1rem" : 0 }}>
          Redirecting to {TARGET_URL} in {secondsRemaining} seconds.
        </p>
        {enableRedirectNowButton && (
          <button
            type="button"
            onClick={handleRedirectNow}
            style={{
              marginTop: "0.5rem",
              padding: "0.5rem 1rem",
              borderRadius: "4px",
              border: "1px solid #000000",
              backgroundColor: "#ffffff",
              cursor: "pointer"
            }}
          >
            Redirect now
          </button>
        )}
      </div>
    </main>
  );
}
