"use client";

import {
  useEffect,
  useId,
  useRef,
  useState,
  useTransition,
  type FormEvent,
} from "react";
import { loginAction } from "@/core/auth/actions";

export type AuthModalView = "login" | "register";

type AuthModalProps = {
  open: boolean;
  view: AuthModalView;
  onViewChange: (view: AuthModalView) => void;
  onClose: () => void;
};

export function AuthModal({
  open,
  view,
  onViewChange,
  onClose,
}: AuthModalProps) {
  const titleId = useId();
  const panelRef = useRef<HTMLDivElement>(null);
  const [visible, setVisible] = useState(false);
  const [rendered, setRendered] = useState(false);

  const [loginError, setLoginError] = useState<string | null>(null);
  const [registerError, setRegisterError] = useState<string | null>(null);
  const [alternatives, setAlternatives] = useState<string[]>([]);
  const [successSlug, setSuccessSlug] = useState<string | null>(null);
  const [successSiteHost, setSuccessSiteHost] = useState<string | null>(null);
  const [successSiteUrl, setSuccessSiteUrl] = useState<string | null>(null);
  const [pendingCredentials, setPendingCredentials] = useState<{
    email: string;
    password: string;
  } | null>(null);
  const [pending, startTransition] = useTransition();

  useEffect(() => {
    if (open) {
      setRendered(true);
      const frame = requestAnimationFrame(() => setVisible(true));
      return () => cancelAnimationFrame(frame);
    }
    setVisible(false);
    const timer = window.setTimeout(() => setRendered(false), 280);
    return () => window.clearTimeout(timer);
  }, [open]);

  useEffect(() => {
    if (!open) return;

    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") onClose();
    };
    window.addEventListener("keydown", onKeyDown);

    const focusTimer = window.setTimeout(() => {
      const first = panelRef.current?.querySelector<HTMLElement>(
        "input, button, [href], select, textarea",
      );
      first?.focus();
    }, 40);

    return () => {
      document.body.style.overflow = previousOverflow;
      window.removeEventListener("keydown", onKeyDown);
      window.clearTimeout(focusTimer);
    };
  }, [open, onClose]);

  useEffect(() => {
    if (!open) {
      setSuccessSlug(null);
      setSuccessSiteHost(null);
      setSuccessSiteUrl(null);
      setPendingCredentials(null);
      return;
    }
    setLoginError(null);
    setRegisterError(null);
    setAlternatives([]);
    // Leaving the success panel for the login tab clears it.
    if (view !== "register") {
      setSuccessSlug(null);
      setSuccessSiteHost(null);
      setSuccessSiteUrl(null);
      setPendingCredentials(null);
    }
  }, [view, open]);

  if (!rendered) return null;

  function handleLogin(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setLoginError(null);
    const form = new FormData(event.currentTarget);
    const email = String(form.get("email") ?? "");
    const password = String(form.get("password") ?? "");

    startTransition(async () => {
      try {
        const result = await loginAction(email, password);
        if (!result.ok) {
          setLoginError(result.error);
        }
        // Success: server action redirects with the session cookie set.
      } catch {
        // Redirect / navigation in progress
      }
    });
  }

  function handleRegister(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setRegisterError(null);
    setAlternatives([]);
    const form = new FormData(event.currentTarget);

    startTransition(async () => {
      const payload = {
        name: String(form.get("name") ?? ""),
        email: String(form.get("email") ?? ""),
        password: String(form.get("password") ?? ""),
        studioName: String(form.get("studioName") ?? ""),
        slug: String(form.get("slug") ?? "") || undefined,
      };

      const res = await fetch("/api/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      const data = (await res.json()) as {
        error?: string;
        alternatives?: string[];
        slug?: string;
        site?: string;
        siteHost?: string;
        environment?: "local" | "online";
      };

      if (!res.ok) {
        setRegisterError(data.error ?? "Registration failed");
        setAlternatives(data.alternatives ?? []);
        return;
      }

      setPendingCredentials({
        email: payload.email.trim().toLowerCase(),
        password: payload.password,
      });
      setSuccessSlug(data.slug ?? "");
      setSuccessSiteHost(data.siteHost ?? null);
      setSuccessSiteUrl(data.site ?? null);
    });
  }

  function handleOpenDashboard() {
    if (!pendingCredentials) {
      onViewChange("login");
      return;
    }

    setRegisterError(null);
    startTransition(async () => {
      try {
        const result = await loginAction(
          pendingCredentials.email,
          pendingCredentials.password,
        );

        if (!result.ok) {
          setSuccessSlug(null);
          setPendingCredentials(null);
          onViewChange("login");
          setLoginError(result.error);
        }
        // Success: server action redirects with the session cookie set.
      } catch {
        // Redirect / navigation in progress
      }
    });
  }

  return (
    <div
      className={`archi-modal-root ${visible ? "is-open" : ""}`}
      role="presentation"
    >
      <button
        type="button"
        className="archi-modal-backdrop"
        aria-label="Close dialog"
        onClick={onClose}
      />

      <div
        ref={panelRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        className="archi-modal-panel"
      >
        <div className="archi-modal-glow" aria-hidden />

        <div className="relative flex items-start justify-between gap-4">
          <div>
            <div className="mb-3 flex items-center gap-2">
              <span className="flex h-8 w-8 items-center justify-center rounded-lg bg-[var(--archi-gold)]/15">
                <ArchMark className="h-4 w-4" />
              </span>
              <span className="text-[11px] font-semibold tracking-[0.22em] text-[var(--archi-gold-bright)] uppercase">
                ARCHI
              </span>
            </div>
            <h2
              id={titleId}
              className="font-[family-name:var(--font-display)] text-2xl font-bold tracking-tight text-white sm:text-[1.75rem]"
            >
              {successSlug
                ? "Studio ready"
                : view === "login"
                  ? "Welcome back"
                  : "Start for free"}
            </h2>
            <p className="mt-1.5 text-sm text-white/55">
              {successSlug
                ? "Your studio space is ready on ARCHI."
                : view === "login"
                  ? "Sign in to manage your studio dashboard."
                  : "Create your account and claim your subdomain."}
            </p>
          </div>

          <button
            type="button"
            onClick={onClose}
            className="rounded-lg border border-white/10 bg-white/5 p-2 text-white/70 transition hover:bg-white/10 hover:text-white"
            aria-label="Close"
          >
            <CloseIcon />
          </button>
        </div>

        {!successSlug ? (
          <div
            className="mt-6 grid grid-cols-2 rounded-xl bg-white/[0.04] p-1 ring-1 ring-white/10"
            role="tablist"
            aria-label="Authentication mode"
          >
            <button
              type="button"
              role="tab"
              aria-selected={view === "login"}
              className={`rounded-lg px-3 py-2.5 text-sm font-medium transition ${
                view === "login"
                  ? "bg-[var(--archi-gold)] text-[var(--archi-dark)] shadow"
                  : "text-white/60 hover:text-white"
              }`}
              onClick={() => onViewChange("login")}
            >
              Login
            </button>
            <button
              type="button"
              role="tab"
              aria-selected={view === "register"}
              className={`rounded-lg px-3 py-2.5 text-sm font-medium transition ${
                view === "register"
                  ? "bg-[var(--archi-gold)] text-[var(--archi-dark)] shadow"
                  : "text-white/60 hover:text-white"
              }`}
              onClick={() => onViewChange("register")}
            >
              Start Free
            </button>
          </div>
        ) : null}

        <div className="mt-6">
          {successSlug ? (
            <div className="space-y-5">
              <div className="rounded-xl border border-[var(--archi-gold)]/30 bg-[var(--archi-gold)]/10 px-4 py-4">
                <p className="text-sm text-white/80">
                  Your studio site for this environment is ready at{" "}
                  {successSiteUrl ? (
                    <a
                      href={successSiteUrl}
                      target="_blank"
                      rel="noreferrer"
                      className="font-semibold text-[var(--archi-gold-bright)] underline-offset-2 hover:underline"
                    >
                      {successSiteHost ?? successSlug}
                    </a>
                  ) : (
                    <span className="font-semibold text-[var(--archi-gold-bright)]">
                      {successSiteHost ?? successSlug}
                    </span>
                  )}
                  . Subdomains are provisioned automatically from your hosting
                  environment — no manual DNS for local development.
                </p>
              </div>
              <button
                type="button"
                className="archi-modal-primary"
                disabled={pending}
                onClick={handleOpenDashboard}
              >
                {pending ? "Opening dashboard…" : "Open dashboard"}
                <ArrowRight />
              </button>
            </div>
          ) : view === "login" ? (
            <form onSubmit={handleLogin} className="space-y-4">
              <Field
                label="Email"
                name="email"
                type="email"
                autoComplete="email"
                required
                placeholder="you@studio.com"
              />
              <Field
                label="Password"
                name="password"
                type="password"
                autoComplete="current-password"
                required
                minLength={12}
                placeholder="••••••••••••"
              />
              {loginError ? (
                <p className="text-sm text-red-300" role="alert">
                  {loginError}
                </p>
              ) : null}
              <button
                type="submit"
                disabled={pending}
                className="archi-modal-primary"
              >
                {pending ? "Signing in…" : "Sign in"}
                {!pending ? <ArrowRight /> : null}
              </button>
            </form>
          ) : (
            <form onSubmit={handleRegister} className="space-y-3.5">
              <div className="grid gap-3.5 sm:grid-cols-2">
                <Field
                  label="Your name"
                  name="name"
                  required
                  autoComplete="name"
                  placeholder="Alex Rivera"
                />
                <Field
                  label="Email"
                  name="email"
                  type="email"
                  required
                  autoComplete="email"
                  placeholder="you@studio.com"
                />
              </div>
              <Field
                label="Password"
                name="password"
                type="password"
                required
                minLength={12}
                autoComplete="new-password"
                placeholder="At least 12 characters"
                hint="Use 12+ characters for studio account security."
              />
              <Field
                label="Studio name"
                name="studioName"
                required
                placeholder="Atelier North"
              />
              <Field
                label="Preferred slug"
                name="slug"
                placeholder="atelier-north"
                hint="Optional — auto-assigned subdomain for this environment"
              />
              {registerError ? (
                <p className="text-sm text-red-300" role="alert">
                  {registerError}
                </p>
              ) : null}
              {alternatives.length > 0 ? (
                <p className="text-sm text-white/50">
                  Try: {alternatives.join(", ")}
                </p>
              ) : null}
              <button
                type="submit"
                disabled={pending}
                className="archi-modal-primary"
              >
                {pending ? "Creating studio…" : "Create free studio"}
                {!pending ? <ArrowRight /> : null}
              </button>
              <p className="text-center text-[12px] text-white/40">
                No credit card · Cancel anytime · Setup in minutes
              </p>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}

function Field({
  label,
  name,
  type = "text",
  required,
  placeholder,
  autoComplete,
  minLength,
  hint,
}: {
  label: string;
  name: string;
  type?: string;
  required?: boolean;
  placeholder?: string;
  autoComplete?: string;
  minLength?: number;
  hint?: string;
}) {
  const id = useId();
  return (
    <label htmlFor={id} className="block">
      <span className="mb-1.5 block text-[12px] font-medium tracking-wide text-white/65">
        {label}
      </span>
      <input
        id={id}
        name={name}
        type={type}
        required={required}
        placeholder={placeholder}
        autoComplete={autoComplete}
        minLength={minLength}
        className="archi-modal-input"
      />
      {hint ? (
        <span className="mt-1.5 block text-[11px] text-white/35">{hint}</span>
      ) : null}
    </label>
  );
}

function ArchMark({ className = "h-4 w-4" }: { className?: string }) {
  return (
    <svg viewBox="0 0 32 32" className={className} aria-hidden fill="none">
      <path
        d="M16 3L28 28H22.5L19.7 21.2H12.3L9.5 28H4L16 3Z"
        fill="var(--archi-gold)"
      />
      <path d="M13.4 18.2H18.6L16 12.2L13.4 18.2Z" fill="#0b0b0c" />
    </svg>
  );
}

function CloseIcon() {
  return (
    <svg viewBox="0 0 16 16" className="h-4 w-4" aria-hidden fill="none">
      <path
        d="M4 4l8 8M12 4l-8 8"
        stroke="currentColor"
        strokeWidth="1.6"
        strokeLinecap="round"
      />
    </svg>
  );
}

function ArrowRight() {
  return (
    <svg viewBox="0 0 16 16" className="h-4 w-4" aria-hidden fill="none">
      <path
        d="M3 8h10M9 4l4 4-4 4"
        stroke="currentColor"
        strokeWidth="1.6"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}
