"use client";

import { ReactNode, FormEvent, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth-context";
import { homeForRole } from "@/lib/roles";
import { ApiError } from "@/lib/api/shared";
import { Spinner } from "@/components/Loading";

interface AuthFormProps {
  children: ReactNode;
  mode: "login" | "signup";
  /** Fallback destination; role-based home is preferred, and ?next= wins. */
  redirectTo?: string;
  submitLabel?: string;
}

export default function AuthForm({ children, mode, redirectTo, submitLabel }: AuthFormProps) {
  const router = useRouter();
  const { login, signup } = useAuth();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError(null);
    const fd = new FormData(e.currentTarget);
    setLoading(true);

    try {
      let role: string;
      if (mode === "login") {
        const user = await login(String(fd.get("email") ?? ""), String(fd.get("password") ?? ""));
        role = user.role;
      } else {
        const chosen = (String(fd.get("role") ?? "tenant") as "tenant" | "landlord");
        const user = await signup({
          name: String(fd.get("name") ?? ""),
          email: String(fd.get("email") ?? ""),
          phone: String(fd.get("phone") ?? ""),
          password: String(fd.get("password") ?? ""),
          confirmPassword: String(fd.get("confirm-password") ?? ""),
          role: chosen,
          agreedToTerms: fd.get("terms") === "on",
        });
        role = user.role;
      }

      const next = new URLSearchParams(window.location.search).get("next");
      // A brand-new landlord goes straight into KYC.
      const dest = next
        ?? (mode === "signup" && role === "landlord" ? "/kyc" : homeForRole(role) || redirectTo || "/dashboard");
      router.push(dest);
      router.refresh();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : "Something went wrong. Please try again.");
      setLoading(false);
    }
  }

  return (
    <form className="flex flex-col" onSubmit={handleSubmit}>
      {children}

      {error && (
        <div className="mb-4 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
          {error}
        </div>
      )}

      <button
        type="submit"
        disabled={loading}
        className="inline-flex items-center justify-center gap-2 font-semibold text-sm px-6 py-3 rounded-pill bg-forest text-white hover:bg-forest-deep transition-colors disabled:opacity-60"
      >
        {loading ? <><Spinner size="sm" />{submitLabel ?? "Please wait…"}</> : mode === "login" ? "Log in" : "Create account"}
      </button>

      {loading && (
        <div className="fixed inset-0 z-50 bg-white/60 backdrop-blur-sm flex items-center justify-center">
          <div className="flex flex-col items-center gap-3 text-forest">
            <Spinner size="lg" />
            <span className="text-sm text-ink-soft font-medium">{submitLabel ?? "Please wait…"}</span>
          </div>
        </div>
      )}
    </form>
  );
}
