"use client";

import Link from "next/link";
import { FormEvent, useEffect, useState, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useAuth } from "@/context/AuthContext";
import { startSocialLogin, sdk, isLoginCredentialsError } from "@/lib/auth";
import { GoogleIcon } from "@/components/ui/GoogleIcon";
import { PasswordField } from "@/components/ui/PasswordField";
import { accountNav, displayFirstName } from "@/lib/account-nav";

type Mode = "login" | "register";

const fieldClass =
  "w-full border border-black/12 bg-transparent px-4 py-3 text-[0.95rem] text-ot-ink outline-none placeholder:text-ot-muted/55 focus:border-ot-green transition";

const labelClass =
  "ot-label-condensed text-[11px] tracking-[0.16em] text-ot-ink";

function AuthSeal() {
  return (
    <div className="flex flex-col items-center">
      {/* eslint-disable-next-line @next/next/no-img-element */}
      <img
        src="/brand/ot-club-seal.png"
        alt="OT Club 1976"
        className="h-16 w-16 object-contain select-none"
        draggable={false}
      />
    </div>
  );
}

function AccountInner() {
  const router = useRouter();
  const params = useSearchParams();
  const initial = (params.get("mode") as Mode) || "login";
  const prefillEmail = params.get("email") || "";
  const [mode, setMode] = useState<Mode>(
    initial === "register" ? "register" : "login"
  );
  const { customer, loading, login, register, logout } = useAuth();
  const [error, setError] = useState<string | null>(null);
  const [info, setInfo] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [hasGoogle, setHasGoogle] = useState(true);
  const [password, setPassword] = useState("");
  const [confirm, setConfirm] = useState("");

  useEffect(() => {
    if (params.get("mode") === "forgot") {
      router.replace("/account/reset-password");
      return;
    }
    setMode(initial === "register" ? "register" : "login");
  }, [initial, params, router]);

  useEffect(() => {
    sdk.auth
      .listProviders("customer")
      .then((res) => {
        const ids = (res.providers || []).map(
          (p: { id?: string; provider?: string }) => p.id || p.provider || ""
        );
        setHasGoogle(ids.includes("google"));
      })
      .catch(() => setHasGoogle(true));
  }, []);

  if (loading) {
    return (
      <div className="min-h-[60vh] flex items-center justify-center text-ot-muted">
        Cargando sesión…
      </div>
    );
  }

  if (customer) {
    const fullName = [customer.first_name, customer.last_name]
      .filter(Boolean)
      .join(" ");
    const name = displayFirstName(customer);
    const links = accountNav.filter((item) => item.href !== "/account");

    return (
      <section className="bg-ot-cream min-h-[calc(100vh-8rem)]">
        <div className="ot-container py-14 md:py-20 max-w-xl">
          <div className="text-center">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src="/brand/ot-club-seal.png"
              alt="OT Club 1976"
              className="mx-auto h-20 w-20 object-contain select-none"
              draggable={false}
            />
            <p className="ot-eyebrow text-ot-gold mt-7">Club 1976</p>
            <h1
              className="mt-2 text-[2.35rem] md:text-[2.85rem] leading-[1.1] tracking-tight text-ot-ink"
              style={{
                fontFamily: "var(--font-fraunces), Fraunces, Georgia, serif",
              }}
            >
              Hola, {name}
            </h1>
            <p className="mt-3 text-sm text-ot-muted leading-relaxed">
              {fullName ? (
                <>
                  <span className="text-ot-ink/80">{fullName}</span>
                  <span className="mx-2 text-ot-muted/40">·</span>
                </>
              ) : null}
              {customer.email}
            </p>
          </div>

          <nav className="mt-10 space-y-2" aria-label="Menú de cuenta">
            {links.map((item) => {
              const Icon = item.icon;
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  className="group flex items-center gap-4 border border-black/10 bg-white/70 px-4 py-4 transition hover:border-ot-green/35 hover:bg-white"
                >
                  <span className="grid h-10 w-10 shrink-0 place-items-center border border-black/8 text-ot-green bg-ot-cream">
                    <Icon size={18} strokeWidth={1.6} />
                  </span>
                  <span className="min-w-0 flex-1 text-left">
                    <span className="block text-[15px] text-ot-ink tracking-wide">
                      {item.label}
                    </span>
                    <span className="mt-0.5 block text-[12px] text-ot-muted leading-snug">
                      {item.hint}
                    </span>
                  </span>
                  <span
                    className="text-ot-muted/50 group-hover:text-ot-green transition text-lg leading-none"
                    aria-hidden
                  >
                    ›
                  </span>
                </Link>
              );
            })}
          </nav>

          <div className="mt-10 flex flex-col items-center gap-3">
            <button
              type="button"
              className="ot-btn ot-btn-ghost !px-8"
              onClick={async () => {
                await logout();
                router.push("/account");
                router.refresh();
              }}
            >
              Cerrar sesión
            </button>
            <Link
              href="/shop"
              className="text-[11px] tracking-[0.16em] uppercase text-ot-muted hover:text-ot-green"
            >
              Seguir comprando
            </Link>
          </div>
        </div>
      </section>
    );
  }

  const onLogin = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError(null);
    setBusy(true);
    const fd = new FormData(e.currentTarget);
    try {
      await login(String(fd.get("email")), String(fd.get("password")));
      window.location.assign("/");
      return;
    } catch (err) {
      setError(err instanceof Error ? err.message : "No se pudo iniciar sesión");
    } finally {
      setBusy(false);
    }
  };

  const onRegister = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError(null);
    setBusy(true);
    const fd = new FormData(e.currentTarget);
    const password = String(fd.get("password"));
    const confirm = String(fd.get("confirm"));
    if (password !== confirm) {
      setError("Las claves de OLD TENNIS no coinciden");
      setBusy(false);
      return;
    }
    if (password.length < 8) {
      setError("La clave de OLD TENNIS debe tener al menos 8 caracteres");
      setBusy(false);
      return;
    }
    try {
      await register({
        email: String(fd.get("email")),
        password,
        firstName: String(fd.get("firstName")),
        lastName: String(fd.get("lastName")),
      });
      window.location.assign("/");
      return;
    } catch (err) {
      setError(err instanceof Error ? err.message : "No se pudo crear la cuenta");
    } finally {
      setBusy(false);
    }
  };

  const startGoogle = async () => {
    setError(null);
    if (!hasGoogle) {
      setError("Google aún no está activo.");
      return;
    }
    try {
      await startSocialLogin("google");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Error con Google");
    }
  };

  const switchMode = (next: Mode) => {
    setMode(next);
    setError(null);
    setInfo(null);
    setPassword("");
    setConfirm("");
  };

  return (
    <section className="bg-ot-cream min-h-[calc(100vh-8rem)] flex items-center justify-center px-4 py-12 md:py-16">
      <div className="w-full max-w-[400px]">
        <AuthSeal />

        <div className="mt-7 text-center">
          <h1
            className="text-[1.85rem] sm:text-[2.15rem] leading-[1.15] tracking-tight text-ot-ink"
            style={{
              fontFamily: "var(--font-fraunces), Fraunces, Georgia, serif",
            }}
          >
            {mode === "login" ? "Bienvenido de nuevo" : "Únete al club"}
          </h1>
          <p className="mt-3 text-[0.95rem] leading-relaxed text-ot-muted max-w-[34ch] mx-auto">
            {mode === "login"
              ? "Inicia sesión para ver tus pedidos y guardar tus piezas favoritas."
              : "Crea tu cuenta OLD TENNIS y recibe lanzamientos, ofertas y acceso Club 1976."}
          </p>
        </div>

        {mode === "login" ? (
          <form onSubmit={onLogin} className="mt-9 space-y-5">
            <div>
              <label htmlFor="login-email" className={labelClass}>
                Correo
              </label>
              <input
                id="login-email"
                name="email"
                type="email"
                autoComplete="email"
                required
                defaultValue={prefillEmail}
                placeholder="tucorreo@ejemplo.com"
                className={`${fieldClass} mt-2`}
              />
            </div>

            <div>
              <div className="flex items-end justify-between gap-3 mb-2">
                <label htmlFor="login-password" className={labelClass}>
                  Contraseña
                </label>
                <Link
                  href="/account/reset-password"
                  className="text-[12px] text-ot-muted hover:text-ot-green underline-offset-2 hover:underline"
                >
                  ¿Olvidaste tu contraseña?
                </Link>
              </div>
              <PasswordField
                name="password"
                placeholder="••••••••"
                autoComplete="current-password"
                value={password}
                onChange={setPassword}
                inputClassName={fieldClass}
              />
            </div>

            <button
              className="ot-btn w-full mt-1 tracking-[0.14em]"
              type="submit"
              disabled={busy}
            >
              {busy ? "Entrando…" : "Iniciar sesión"}
            </button>
          </form>
        ) : (
          <form onSubmit={onRegister} className="mt-9 space-y-4">
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label htmlFor="reg-first" className={labelClass}>
                  Nombre
                </label>
                <input
                  id="reg-first"
                  name="firstName"
                  autoComplete="given-name"
                  required
                  placeholder="Ana"
                  className={`${fieldClass} mt-2`}
                />
              </div>
              <div>
                <label htmlFor="reg-last" className={labelClass}>
                  Apellido
                </label>
                <input
                  id="reg-last"
                  name="lastName"
                  autoComplete="family-name"
                  required
                  placeholder="Pérez"
                  className={`${fieldClass} mt-2`}
                />
              </div>
            </div>
            <div>
              <label htmlFor="reg-email" className={labelClass}>
                Correo
              </label>
              <input
                id="reg-email"
                name="email"
                type="email"
                autoComplete="email"
                required
                defaultValue={prefillEmail}
                placeholder="tucorreo@ejemplo.com"
                className={`${fieldClass} mt-2`}
              />
            </div>
            <div>
              <label className={labelClass}>Contraseña</label>
              <div className="mt-2">
                <PasswordField
                  name="password"
                  placeholder="Mínimo 8 caracteres"
                  autoComplete="new-password"
                  showStrength
                  value={password}
                  onChange={setPassword}
                  inputClassName={fieldClass}
                />
              </div>
            </div>
            <div>
              <label className={labelClass}>Confirmar contraseña</label>
              <div className="mt-2">
                <PasswordField
                  name="confirm"
                  placeholder="Repite la contraseña"
                  autoComplete="new-password"
                  value={confirm}
                  onChange={setConfirm}
                  inputClassName={fieldClass}
                />
              </div>
            </div>
            <p className="text-[11px] text-ot-muted leading-relaxed">
              Esta clave es solo para la tienda. No es ni cambia la de Gmail.
            </p>
            <button
              className="ot-btn w-full tracking-[0.14em]"
              type="submit"
              disabled={busy}
            >
              {busy ? "Creando…" : "Crear cuenta"}
            </button>
          </form>
        )}

        <div className="relative my-7 text-center">
          <span className="absolute inset-x-0 top-1/2 border-t border-black/10" />
          <span className="relative z-[1] bg-ot-cream px-3 text-[11px] tracking-[0.18em] uppercase text-ot-muted">
            o
          </span>
        </div>

        <button
          type="button"
          className="w-full border border-black/15 bg-white px-4 py-3 text-sm flex items-center justify-center gap-3 hover:border-ot-green/40 disabled:opacity-50 transition"
          disabled={busy}
          onClick={startGoogle}
        >
          <GoogleIcon />
          Continuar con Google
        </button>

        {error && mode === "login" && isLoginCredentialsError(error) ? (
          <div className="mt-5 border border-red-700/20 bg-red-700/[0.04] px-3.5 py-3 text-sm text-red-800">
            <p className="font-medium">Correo o contraseña incorrectos.</p>
            <ul className="mt-2 space-y-1.5 text-[13px] leading-relaxed">
              <li>
                Si sueles entrar con Google, usa{" "}
                <button
                  type="button"
                  className="underline underline-offset-2"
                  onClick={startGoogle}
                >
                  Continuar con Google
                </button>
                .
              </li>
              <li>
                Si aún no tienes cuenta,{" "}
                <button
                  type="button"
                  className="underline underline-offset-2"
                  onClick={() => switchMode("register")}
                >
                  regístrate
                </button>
                .
              </li>
              <li>
                Si olvidaste tu contraseña,{" "}
                <Link
                  href="/account/reset-password"
                  className="underline underline-offset-2"
                >
                  restablécela
                </Link>
                .
              </li>
            </ul>
          </div>
        ) : (
          error && <p className="mt-5 text-sm text-red-700 text-center">{error}</p>
        )}
        {info && (
          <p className="mt-5 text-sm text-ot-green text-center">{info}</p>
        )}

        <p className="mt-8 text-center text-[0.95rem] text-ot-muted">
          {mode === "login" ? (
            <>
              ¿Primera vez en Old Tennis?{" "}
              <button
                type="button"
                onClick={() => switchMode("register")}
                className="text-ot-ink underline underline-offset-[3px] hover:text-ot-green"
              >
                Crea tu cuenta
              </button>
            </>
          ) : (
            <>
              ¿Ya tienes cuenta?{" "}
              <button
                type="button"
                onClick={() => switchMode("login")}
                className="text-ot-ink underline underline-offset-[3px] hover:text-ot-green"
              >
                Inicia sesión
              </button>
            </>
          )}
        </p>
      </div>
    </section>
  );
}

export default function AccountPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-[60vh] flex items-center justify-center text-ot-muted">
          Cargando…
        </div>
      }
    >
      <AccountInner />
    </Suspense>
  );
}
