"use client";

import { useRouter } from "next/navigation";
import { createContext, useContext, useEffect, useState, type ComponentProps, type FormEvent } from "react";
import { ApiError, errorMessage, login, refreshSession } from "@/app/(admin)/_lib/api";
import type { PublicLocale } from "@/app/(admin)/_lib/queries";
import { homeForRole, isAdminRole } from "@/app/(admin)/_lib/roles";

type State = { busy: boolean; error: string | null };
const Ctx = createContext<State>({ busy: false, error: null });

/** GET /public/locale — sent with the login so the API can record where it came from. */
async function detectedRegion(): Promise<string | undefined> {
  try {
    const res = await fetch("/api/v1/public/locale", { cache: "no-store" });
    if (!res.ok) return undefined;
    const { data } = (await res.json()) as { data: PublicLocale };
    // Only a real IP detection; "default" is just Global for an unknown IP.
    return data.detection.method === "ip" ? data.region.code : undefined;
  } catch {
    return undefined;
  }
}

/** Admin pages live under another root layout, so they need a full page load. */
function go(router: ReturnType<typeof useRouter>, href: string) {
  if (href.startsWith("/admin")) window.location.assign(href);
  else router.replace(href);
}

/**
 * The one login form for the whole site (website users and admins). Renders the
 * same <form> as before; on success it sends the user where their role belongs
 * (admin roles → /admin/dashboard, everyone else → the website).
 */
export function LoginForm({ children, ...props }: ComponentProps<"form">) {
  const router = useRouter();
  const [state, setState] = useState<State>({ busy: false, error: null });
  const [region, setRegion] = useState<string | undefined>();

  // Already signed in (refresh cookie still valid): skip the form.
  useEffect(() => {
    let alive = true;
    refreshSession().then((d) => {
      if (alive && d) go(router, homeForRole(d.user.role));
    });
    detectedRegion().then((r) => alive && setRegion(r));
    return () => {
      alive = false;
    };
  }, [router]);

  const onSubmit = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const fd = new FormData(e.currentTarget);
    setState({ busy: true, error: null });
    try {
      const user = await login(String(fd.get("email") ?? "").trim(), String(fd.get("password") ?? ""), region);
      go(router, homeForRole(user.role));
      if (!isAdminRole(user.role)) setState({ busy: false, error: null });
    } catch (err) {
      setState({
        busy: false,
        error:
          err instanceof ApiError && err.status === 429
            ? "Too many sign-in attempts. Wait a minute and try again."
            : err instanceof ApiError && err.status === 401
              ? "Invalid email or password. After 5 wrong attempts the account is locked for 15 minutes."
              : errorMessage(err),
      });
    }
  };

  return (
    <Ctx.Provider value={state}>
      <form {...props} onSubmit={onSubmit}>
        {children}
      </form>
    </Ctx.Provider>
  );
}

/** The form's submit button; shows "Logging in…" while signing in (as the static page did). */
export function LoginSubmit({ children, style, ...props }: ComponentProps<"button">) {
  const { busy } = useContext(Ctx);
  return (
    <button {...props} disabled={busy} aria-busy={busy} style={busy ? { ...style, opacity: 0.7 } : style}>
      {busy ? "Logging in…" : children}
    </button>
  );
}

/** Error line under the password field; renders nothing until a sign-in fails. */
export function LoginError({ className }: { className?: string }) {
  const { error } = useContext(Ctx);
  if (!error) return null;
  return (
    <p role="alert" className={className}>
      {error}
    </p>
  );
}
