"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { api, ApiError, ensureSession } from "../../lib/api";
import { BrandMark, BrandWord, IconGoogle, IconKey } from "../../components/icons";
import { AVATAR_PALETTE } from "../../lib/avatar";

/**
 * The prototype's auth stage (Voxi.dc.html, `isAuth` branch): a 1.05fr/1fr
 * split with a gradient hero on the left and the form on the right.
 *
 * The hero's face pile and "Acme Inc. runs 245 people" line are design
 * copy — there is no workspace context before sign-in to source them from,
 * so they stay as the design wrote them.
 */
export default function LoginPage() {
  const router = useRouter();
  const [mode, setMode] = useState<"login" | "signup">("login");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [name, setName] = useState("");
  const [message, setMessage] = useState<string | null>(null);
  const [verificationLink, setVerificationLink] = useState<string | null>(null);
  const [isError, setIsError] = useState(false);
  const [busy, setBusy] = useState(false);
  const [checkingSession, setCheckingSession] = useState(true);

  useEffect(() => {
    let cancelled = false;
    ensureSession().then((ok) => {
      if (cancelled) return;
      if (ok) router.replace("/workspaces");
      else setCheckingSession(false);
    });
    return () => {
      cancelled = true;
    };
  }, [router]);

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    setBusy(true);
    setMessage(null);
    setIsError(false);
    try {
      if (mode === "signup") {
        const result = await api.signup({ email, password, name });
        setVerificationLink(result.verificationLink);
        setMessage("Account created. Use the verification link below to verify your email, then sign in.");
        setMode("login");
      } else {
        await api.login({ email, password });
        router.replace("/workspaces");
      }
    } catch (err) {
      setIsError(true);
      setMessage(err instanceof ApiError ? JSON.stringify(err.body) : String(err));
    } finally {
      setBusy(false);
    }
  }

  function requestReset() {
    router.push(email ? `/reset-password?email=${encodeURIComponent(email)}` : "/reset-password");
  }

  if (checkingSession) {
    return <main className="auth-shell" aria-busy="true" />;
  }

  return (
    <main className="auth-shell">
      <section className="auth-hero">
        <div className="auth-brand">
          <span className="auth-brand-chip">
            <BrandMark />
          </span>
          <span className="auth-brand-word"><BrandWord tone="invert" /></span>
        </div>

        <div className="auth-hero-body">
          <p className="auth-hero-title">Where the work actually happens.</p>
          <p className="auth-hero-sub">
            Channels, threads, Connect and docs in one calm place. Acme Inc. runs 245 people on connectHUB.
          </p>
          <div className="auth-faces" aria-hidden="true">
            {["LD", "ZM", "MB", "EC", "OR"].map((face, index) => {
              const color = AVATAR_PALETTE[index]!;
              return (
                <span className="auth-face" key={face} style={{ background: color.bg, color: color.fg }}>
                  {face}
                </span>
              );
            })}
          </div>
        </div>

        <span className="auth-blob-a" aria-hidden="true" />
        <span className="auth-blob-b" aria-hidden="true" />

        <div className="auth-hero-foot">SOC 2 Type II · Encrypted in transit and at rest</div>
      </section>

      <section className="auth-panel">
        <div className="auth-form">
          <h1 className="auth-title">{mode === "signup" ? "Create your account" : "Sign in to connectHUB"}</h1>
          <p className="auth-sub">
            {mode === "signup" ? "Use your work email to get started." : "Use your work email to continue."}
          </p>

          <form onSubmit={submit}>
            {mode === "signup" && (
              <>
                <label className="auth-label" htmlFor="auth-name">
                  Full name
                </label>
                <input
                  id="auth-name"
                  className="auth-input"
                  placeholder="Sarah Parker"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  required
                />
              </>
            )}

            <label className="auth-label" htmlFor="auth-email">
              Work email
            </label>
            <input
              id="auth-email"
              className="auth-input"
              type="email"
              placeholder="sarah@acme.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
            />

            <label className="auth-label" htmlFor="auth-password">
              Password
            </label>
            <input
              id="auth-password"
              className="auth-input last"
              type="password"
              placeholder="••••••••••"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              minLength={8}
              required
            />

            <div className="auth-forgot">
              <button type="button" onClick={requestReset}>
                Forgot password?
              </button>
            </div>

            <button className="auth-submit" type="submit" disabled={busy}>
              {busy ? "Working…" : mode === "signup" ? "Create account" : "Continue"}
            </button>
          </form>

          <div className="auth-or">
            <i />
            <span>OR</span>
            <i />
          </div>

          {/* The design shows Google and SSO. Neither identity provider is
              wired up (OD-3 in SPIKES.md is still a spike), so these are
              disabled rather than rendered as working buttons that 404. */}
          <div className="auth-alts">
            <button className="auth-alt" type="button" disabled title="Not configured yet">
              <IconGoogle />
              Continue with Google
            </button>
            <button className="auth-alt" type="button" disabled title="Not configured yet">
              <IconKey />
              Continue with SSO
            </button>
          </div>

          <p className="auth-foot">
            {mode === "signup" ? "Already have an account? " : "New to connectHUB? "}
            <button type="button" onClick={() => setMode(mode === "signup" ? "login" : "signup")}>
              {mode === "signup" ? "Sign in" : "Create an account"}
            </button>
          </p>

          {message && <p className={isError ? "auth-message error" : "auth-message"}>{message}</p>}
          {verificationLink && (
            <div className="auth-message verification-link">
              <p>Verification link:</p>
              <a href={verificationLink}>{verificationLink}</a>
            </div>
          )}
        </div>
      </section>
    </main>
  );
}
