import { useState } from "react";
import { api } from "../lib/api";

type Phase = "idle" | "sending" | "requested" | "approved" | "error";

export default function Login() {
  // A denied Google login bounces back here with ?access=requested (we recorded it) or
  // ?access=denied (no usable email). Surface that so the user isn't left on a raw error.
  const params = new URLSearchParams(window.location.search);
  const bounced = params.get("access"); // "requested" | "denied" | null

  const [email, setEmail] = useState("");
  const [phase, setPhase] = useState<Phase>(bounced === "requested" ? "requested" : "idle");
  const [error, setError] = useState("");

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setPhase("sending");
    try {
      const r = await api.requestAccess(email.trim());
      setPhase(r.status === "approved" ? "approved" : "requested");
    } catch {
      setError("Couldn't submit — check the address and try again.");
      setPhase("error");
    }
  }

  const done = phase === "requested" || phase === "approved";

  return (
    <div className="min-h-screen grid place-items-center bg-bg text-fg">
      <div className="glass w-[min(92vw,420px)] rounded-2xl p-10 text-center">
        <div className="text-3xl font-bold tracking-tight">
          Sub<span className="text-accent">feed</span>
        </div>
        <p className="text-muted my-5 leading-relaxed">
          Your subscriptions, filtered your way.
          <br />
          Sign in with your Google account.
        </p>
        <a
          href="/auth/login"
          className="inline-flex items-center gap-2 px-5 py-3 rounded-xl font-semibold bg-accent text-accent-fg hover:opacity-90 transition"
        >
          Sign in with Google
        </a>

        <div className="mt-7 pt-6 border-t border-border text-left">
          {phase === "approved" ? (
            <p className="text-sm text-fg/80">
              You're already approved — just sign in with Google above.
            </p>
          ) : done ? (
            <p className="text-sm text-fg/80">
              Thanks — your request is in. We'll email you when it's approved.
            </p>
          ) : (
            <>
              <div className="text-xs uppercase tracking-wide text-muted mb-2">
                No access yet?
              </div>
              {bounced === "denied" && (
                <p className="text-xs text-muted mb-2">
                  That Google account isn't approved. Request access below.
                </p>
              )}
              <form onSubmit={submit} className="flex items-center gap-2">
                <input
                  type="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@gmail.com"
                  className="flex-1 min-w-0 bg-card border border-border rounded-xl px-3 py-2 text-sm outline-none focus:border-accent"
                />
                <button
                  type="submit"
                  disabled={phase === "sending"}
                  className="shrink-0 px-3 py-2 rounded-xl text-sm font-semibold bg-card border border-border hover:border-accent disabled:opacity-50 transition"
                >
                  {phase === "sending" ? "Sending…" : "Request access"}
                </button>
              </form>
              {error && <p className="text-xs text-red-400 mt-2">{error}</p>}
            </>
          )}
        </div>
      </div>
    </div>
  );
}
