"use client";

import { FormEvent, useEffect, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import { Eye, EyeOff, X } from "lucide-react";
import { useAuth } from "@/context/AuthContext";
import { startSocialLogin } from "@/lib/auth";
import { GoogleIcon } from "@/components/ui/GoogleIcon";

export const HOME_REGISTER_EVENT = "ot:visit-home";

const DISMISS_KEY = "ot_register_dismissed";

const field =
  "w-full border border-black/15 bg-white px-3 py-3 text-sm outline-none focus:border-ot-green";

export function SubscribeModal() {
  const pathname = usePathname();
  const router = useRouter();
  const { customer, loading, register } = useAuth();
  const [open, setOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showPass, setShowPass] = useState(false);

  const isHome = pathname === "/";
  const canShow = !loading && !customer;

  const wasDismissed = () => {
    try {
      return sessionStorage.getItem(DISMISS_KEY) === "1";
    } catch {
      return false;
    }
  };

  const markDismissed = () => {
    try {
      sessionStorage.setItem(DISMISS_KEY, "1");
    } catch {
      /* ignore */
    }
  };

  useEffect(() => {
    if (!canShow || !isHome || wasDismissed()) {
      setOpen(false);
      return;
    }
    const timer = window.setTimeout(() => {
      setError(null);
      setOpen(true);
    }, 1800);
    return () => window.clearTimeout(timer);
  }, [canShow, isHome]);

  useEffect(() => {
    const onVisitHome = () => {
      if (!canShow || wasDismissed()) return;
      setError(null);
      setOpen(true);
    };
    window.addEventListener(HOME_REGISTER_EVENT, onVisitHome);
    return () => window.removeEventListener(HOME_REGISTER_EVENT, onVisitHome);
  }, [canShow]);

  const dismiss = () => {
    markDismissed();
    setOpen(false);
  };

  const startGoogle = async () => {
    setError(null);
    setBusy(true);
    try {
      await startSocialLogin("google");
    } catch (err) {
      setError(err instanceof Error ? err.message : "No se pudo entrar con Google");
      setBusy(false);
    }
  };

  const onSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setError(null);
    const fd = new FormData(e.currentTarget);
    const password = String(fd.get("password") || "");
    if (password.length < 8) {
      setError("La clave debe tener al menos 8 caracteres.");
      return;
    }
    setBusy(true);
    const email = String(fd.get("email") || "")
      .trim()
      .toLowerCase();
    try {
      fetch("/api/subscribe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, source: "home-register-popup" }),
      }).catch(() => undefined);

      await register({
        email,
        password,
        firstName: String(fd.get("firstName") || "").trim(),
        lastName: String(fd.get("lastName") || "").trim(),
      });
      markDismissed();
      setOpen(false);
      router.refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : "No se pudo crear la cuenta");
    } finally {
      setBusy(false);
    }
  };

  if (!open || !canShow) return null;

  return (
    <div className="fixed inset-0 z-[80] flex items-end sm:items-center justify-center p-0 sm:p-6">
      <button
        type="button"
        className="absolute inset-0 bg-ot-green/75"
        aria-label="Cerrar"
        onClick={dismiss}
      />
      <div className="relative w-full max-w-[400px] bg-ot-cream shadow-2xl animate-[ot-fade-up_0.4s_ease] px-6 py-7 sm:px-8 sm:py-8">
        <button
          type="button"
          onClick={dismiss}
          className="absolute right-3.5 top-3.5 text-ot-muted hover:text-ot-ink"
          aria-label="Cerrar"
        >
          <X size={16} />
        </button>

        <p className="ot-eyebrow text-ot-gold">Club 1976</p>
        <h2 className="font-serif text-[2rem] mt-1.5 leading-none text-ot-ink">
          Crea tu cuenta
        </h2>
        <p className="mt-2.5 text-[13px] leading-snug text-ot-muted">
          Ofertas exclusivas y lanzamientos de OLD TENNIS.
        </p>

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

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

        <form onSubmit={onSubmit} className="space-y-2.5">
          <div className="grid grid-cols-2 gap-2.5">
            <input
              name="firstName"
              autoComplete="given-name"
              required
              placeholder="Nombre"
              className={field}
            />
            <input
              name="lastName"
              autoComplete="family-name"
              required
              placeholder="Apellido"
              className={field}
            />
          </div>
          <input
            name="email"
            type="email"
            autoComplete="email"
            required
            placeholder="Email"
            className={field}
          />
          <div className="relative">
            <input
              name="password"
              type={showPass ? "text" : "password"}
              autoComplete="new-password"
              required
              minLength={8}
              placeholder="Clave de OLD TENNIS"
              className={`${field} pr-10`}
            />
            <button
              type="button"
              onClick={() => setShowPass((v) => !v)}
              className="absolute right-2.5 top-1/2 -translate-y-1/2 text-ot-muted hover:text-ot-green"
              aria-label={showPass ? "Ocultar clave" : "Ver clave"}
            >
              {showPass ? <EyeOff size={16} /> : <Eye size={16} />}
            </button>
          </div>
          <button
            className="ot-btn w-full !py-3 !text-[11px] mt-1"
            type="submit"
            disabled={busy}
          >
            {busy ? "Creando…" : "Crear cuenta"}
          </button>
          {error && (
            <p className="text-[12px] leading-snug text-red-700">{error}</p>
          )}
        </form>

        <button
          type="button"
          onClick={dismiss}
          className="mt-5 w-full text-center text-[10px] tracking-[0.18em] uppercase text-ot-muted hover:text-ot-green"
        >
          Ahora no
        </button>
      </div>
    </div>
  );
}
