import { useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { betaAccessStorageKey } from "../components/BetaGate";

const ACCESS_CODE = "jodygavemeaccess123";

export default function BetaAccessPage() {
  const navigate = useNavigate();
  const [code, setCode] = useState("");
  const [touched, setTouched] = useState(false);

  const isValid = useMemo(() => code.trim() === ACCESS_CODE, [code]);
  const isUnlocked = useMemo(
    () => localStorage.getItem(betaAccessStorageKey) === "true",
    []
  );

  const handleSubmit = (event: React.FormEvent) => {
    event.preventDefault();
    setTouched(true);
    if (!isValid) return;
    localStorage.setItem(betaAccessStorageKey, "true");
    navigate("/login", { replace: true });
  };

  return (
    <div className="min-h-screen bg-[--color-bg] flex items-center justify-center px-4 py-10">
      <div className="w-full max-w-xl card p-8 sm:p-10">
        <div className="space-y-3">
          <div className="text-xs uppercase tracking-[0.2em] muted">
            Private beta
          </div>
          <h1 className="text-3xl sm:text-4xl font-semibold">
            Welcome to SkyMoney
          </h1>
          <p className="muted">
            This build is private. If you’ve been given access, enter your code
            below. If not, reach out to{" "}
            <a
              href="https://jodyholt.com"
              target="_blank"
              rel="noreferrer"
              className="text-[--color-accent] font-medium hover:underline"
            >
              Jody
            </a>{" "}
            for access.
          </p>
        </div>

        <form onSubmit={handleSubmit} className="mt-6 space-y-4">
          <label className="block text-sm font-medium">
            Access code
            <div className="mt-2">
              <input
                type="text"
                className="input w-full"
                value={code}
                onChange={(event) => {
                  setTouched(true);
                  setCode(event.target.value);
                }}
                placeholder="Enter your code"
                autoComplete="off"
              />
            </div>
          </label>

          {touched && code.length > 0 && !isValid && (
            <div className="text-sm text-red-500">
              That code doesn’t match. Please try again.
            </div>
          )}

          <button
            type="submit"
            className="btn primary w-full"
            disabled={!isValid}
          >
            Continue
          </button>

          {isUnlocked && (
            <button
              type="button"
              className="btn w-full"
              onClick={() => navigate("/login")}
            >
              I already have access
            </button>
          )}
        </form>
      </div>
    </div>
  );
}
