"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2 } from "lucide-react";
import { useForm } from "react-hook-form";
import { useTranslations } from "next-intl";

import { AuthLoadingSpinner } from "@/components/auth/AuthLoadingSpinner";
import { authFormSchema, type AuthFormValues } from "@/components/auth/auth-schemas";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

type AuthTab = "sign-in" | "sign-up";
type AuthView = "main" | "forgot-password" | "reset-confirm";

/** Only allow same-origin relative redirects to avoid open-redirect issues. */
function safeNext(next: string | null): string {
  if (next && next.startsWith("/") && !next.startsWith("//")) return next;
  return "/dashboard";
}

export function AuthPageContent() {
  const t = useTranslations("auto.componentsAuthAuthPageContent");
  const router = useRouter();
  const searchParams = useSearchParams();
  const nextPath = safeNext(searchParams.get("next"));

  const initialTab =
    searchParams.get("tab") === "sign-up" ? "sign-up" : "sign-in";

  const [activeTab, setActiveTab] = useState<AuthTab>(initialTab);
  const [view, setView] = useState<AuthView>("main");
  const [authLoading, setAuthLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);
  const [formMessage, setFormMessage] = useState<string | null>(null);

  // Forgot-password state
  const [resetEmail, setResetEmail] = useState("");
  const [resetOtp, setResetOtp] = useState("");
  const [resetNewPassword, setResetNewPassword] = useState("");

  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm<AuthFormValues>({
    resolver: zodResolver(authFormSchema),
    defaultValues: { email: "", password: "" },
  });

  // Redirect away if already authenticated.
  const checkSession = useCallback(async () => {
    try {
      const res = await fetch("/api/auth/me", { cache: "no-store" });
      const data = await res.json().catch(() => null);
      if (data?.user) {
        router.replace(nextPath);
        return true;
      }
    } catch {
      /* not signed in */
    }
    return false;
  }, [router, nextPath]);

  useEffect(() => {
    let mounted = true;
    checkSession().then((redirected) => {
      if (mounted && !redirected) setAuthLoading(false);
    });
    return () => { mounted = false; };
  }, [checkSession]);

  const handleTabChange = (tab: AuthTab) => {
    setActiveTab(tab);
    setFormError(null);
    setFormMessage(null);
    reset();
  };

  const goBack = () => {
    setView("main");
    setFormError(null);
    setFormMessage(null);
    setResetEmail("");
    setResetOtp("");
    setResetNewPassword("");
  };

  // ── Google OAuth — redirect to identity's start endpoint ──────────────────
  const googleSignIn = () => {
    const base = process.env.NEXT_PUBLIC_API_URL ?? "";
    const returnUrl = `${window.location.origin}/auth/callback?next=${encodeURIComponent(nextPath)}`;
    window.location.href = `${base}/auth/google/start?return_url=${encodeURIComponent(returnUrl)}`;
  };

  // ── Main sign-in / sign-up submit ──────────────────────────────────────────
  const onSubmit = async (values: AuthFormValues) => {
    setSubmitting(true);
    setFormError(null);
    setFormMessage(null);

    const endpoint = activeTab === "sign-in" ? "/api/auth/login" : "/api/auth/register";

    try {
      const res = await fetch(endpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: values.email, password: values.password }),
      });
      const data = await res.json().catch(() => null);

      if (!res.ok) {
        setFormError(data?.error ?? t("genericError"));
        setSubmitting(false);
        return;
      }

      if (data?.registered && !data?.user) {
        setFormMessage(
          data.verificationRequired
            ? t("accountCreatedVerify")
            : t("accountCreatedSignIn")
        );
        setActiveTab("sign-in");
        reset();
        setSubmitting(false);
        return;
      }

      router.replace(nextPath);
      router.refresh();
    } catch {
      setFormError(t("networkError"));
      setSubmitting(false);
    }
  };

  // ── Forgot password — step 1: request OTP ─────────────────────────────────
  const handleForgotRequest = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!resetEmail) return;
    setSubmitting(true);
    setFormError(null);
    try {
      await fetch("/api/auth/password-reset", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: resetEmail }),
      });
      // Always succeed (anti-enumeration)
      setView("reset-confirm");
      setFormMessage(t("resetCodeSent"));
    } catch {
      setFormError(t("networkError"));
    } finally {
      setSubmitting(false);
    }
  };

  // ── Forgot password — step 2: confirm OTP + new password ──────────────────
  const handleResetConfirm = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!resetOtp || !resetNewPassword) return;
    setSubmitting(true);
    setFormError(null);
    try {
      const res = await fetch("/api/auth/password-reset-confirm", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email: resetEmail, otp: resetOtp, new_password: resetNewPassword }),
      });
      const data = await res.json().catch(() => null) as { error?: string } | null;
      if (!res.ok) {
        setFormError(data?.error ?? t("invalidCode"));
      } else {
        setFormMessage(t("passwordUpdated"));
        goBack();
      }
    } catch {
      setFormError(t("networkError"));
    } finally {
      setSubmitting(false);
    }
  };

  if (authLoading) {
    return (
      <div className="flex min-h-[calc(100vh-4rem)] items-center justify-center py-20">
        <AuthLoadingSpinner label={t("checkingAuth")} />
      </div>
    );
  }

  // ── Forgot password views ──────────────────────────────────────────────────
  if (view === "forgot-password" || view === "reset-confirm") {
    return (
      <div className="mx-auto w-full max-w-md px-4 py-12 sm:py-16">
        <div className="text-center">
          <h1 className="font-heading text-2xl font-bold text-neutral-900">
            {view === "forgot-password" ? t("resetTitle") : t("enterCodeTitle")}
          </h1>
          <p className="mt-2 text-sm text-neutral-600">
            {view === "forgot-password"
              ? t("resetSubtitle")
              : t("enterCodeSubtitle", { email: resetEmail })}
          </p>
        </div>

        <div className="mt-8 rounded-xl border border-gray-100 bg-white p-6 shadow-sm">
          {view === "forgot-password" ? (
            <form onSubmit={handleForgotRequest} className="space-y-4" noValidate>
              <div>
                <label htmlFor="reset-email" className="block text-sm font-medium text-neutral-700">
                  {t("emailAddressLabel")}
                </label>
                <input
                  id="reset-email"
                  type="email"
                  value={resetEmail}
                  onChange={(e) => setResetEmail(e.target.value)}
                  disabled={submitting}
                  required
                  className="mt-1.5 w-full rounded-lg border border-gray-100 bg-white px-3 py-2.5 text-sm text-neutral-900 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 disabled:opacity-50"
                />
              </div>
              {formError && <p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">{formError}</p>}
              <Button type="submit" className="w-full" disabled={submitting || !resetEmail}>
                {submitting && <Loader2 className="h-4 w-4 animate-spin" />}
                {t("sendResetCode")}
              </Button>
            </form>
          ) : (
            <form onSubmit={handleResetConfirm} className="space-y-4" noValidate>
              <div>
                <label htmlFor="reset-otp" className="block text-sm font-medium text-neutral-700">
                  {t("resetCodeLabel")}
                </label>
                <input
                  id="reset-otp"
                  type="text"
                  inputMode="numeric"
                  value={resetOtp}
                  onChange={(e) => setResetOtp(e.target.value)}
                  disabled={submitting}
                  required
                  placeholder={t("resetCodePlaceholder")}
                  className="mt-1.5 w-full rounded-lg border border-gray-100 bg-white px-3 py-2.5 text-sm text-neutral-900 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 disabled:opacity-50"
                />
              </div>
              <div>
                <label htmlFor="new-password" className="block text-sm font-medium text-neutral-700">
                  {t("newPasswordLabel")}
                </label>
                <input
                  id="new-password"
                  type="password"
                  autoComplete="new-password"
                  value={resetNewPassword}
                  onChange={(e) => setResetNewPassword(e.target.value)}
                  disabled={submitting}
                  required
                  minLength={8}
                  className="mt-1.5 w-full rounded-lg border border-gray-100 bg-white px-3 py-2.5 text-sm text-neutral-900 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 disabled:opacity-50"
                />
              </div>
              {formError && <p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">{formError}</p>}
              {formMessage && <p className="rounded-lg bg-primary-50 px-3 py-2 text-sm text-primary-700">{formMessage}</p>}
              <Button type="submit" className="w-full" disabled={submitting || !resetOtp || !resetNewPassword}>
                {submitting && <Loader2 className="h-4 w-4 animate-spin" />}
                {t("setNewPassword")}
              </Button>
            </form>
          )}
        </div>

        <button type="button" onClick={goBack} className="mt-4 block w-full text-center text-sm text-neutral-500 hover:text-neutral-700 transition-colors">
          ← {t("backToSignIn")}
        </button>
      </div>
    );
  }

  // ── Main sign-in / sign-up view ────────────────────────────────────────────
  return (
    <div className="mx-auto w-full max-w-md px-4 py-12 sm:py-16">
      <div className="text-center">
        <h1 className="font-heading text-3xl font-bold text-neutral-900">
          {t("welcomeTitle")}
        </h1>
        <p className="mt-2 text-sm text-neutral-600">
          {activeTab === "sign-in"
            ? t("signInSubtitle")
            : t("signUpSubtitle")}
        </p>
      </div>

      <div className="mt-8 flex rounded-lg border border-gray-100 bg-neutral-50 p-1">
        {(["sign-in", "sign-up"] as const).map((tab) => (
          <button
            key={tab}
            type="button"
            onClick={() => handleTabChange(tab)}
            className={cn(
              "flex-1 rounded-md px-4 py-2 text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 focus-visible:ring-offset-2",
              activeTab === tab
                ? "bg-white text-neutral-900 shadow-sm"
                : "text-neutral-600 hover:text-neutral-900"
            )}
          >
            {tab === "sign-in" ? t("signInTab") : t("signUpTab")}
          </button>
        ))}
      </div>

      <div className="mt-6 rounded-xl border border-gray-100 bg-white p-6 shadow-sm">
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate>
          <div>
            <label htmlFor="email" className="block text-sm font-medium text-neutral-700">
              {t("emailLabel")}
            </label>
            <input
              id="email"
              type="email"
              autoComplete="email"
              disabled={submitting}
              className={cn(
                "mt-1.5 w-full rounded-lg border bg-white px-3 py-2.5 text-sm text-neutral-900 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 focus-visible:ring-offset-2 disabled:opacity-50",
                errors.email ? "border-red-300" : "border-gray-100"
              )}
              {...register("email")}
            />
            {errors.email && (
              <p className="mt-1.5 text-xs text-red-600">{errors.email.message}</p>
            )}
          </div>

          <div>
            <div className="flex items-center justify-between">
              <label htmlFor="password" className="block text-sm font-medium text-neutral-700">
                {t("passwordLabel")}
              </label>
              {activeTab === "sign-in" && (
                <button
                  type="button"
                  onClick={() => { setView("forgot-password"); setFormError(null); setFormMessage(null); }}
                  className="text-xs text-primary-600 hover:underline focus-visible:outline-none"
                >
                  {t("forgotPassword")}
                </button>
              )}
            </div>
            <input
              id="password"
              type="password"
              autoComplete={activeTab === "sign-in" ? "current-password" : "new-password"}
              disabled={submitting}
              className={cn(
                "mt-1.5 w-full rounded-lg border bg-white px-3 py-2.5 text-sm text-neutral-900 shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-600 focus-visible:ring-offset-2 disabled:opacity-50",
                errors.password ? "border-red-300" : "border-gray-100"
              )}
              {...register("password")}
            />
            {errors.password && (
              <p className="mt-1.5 text-xs text-red-600">{errors.password.message}</p>
            )}
          </div>

          {formError && (
            <p className="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">{formError}</p>
          )}
          {formMessage && (
            <p className="rounded-lg bg-primary-50 px-3 py-2 text-sm text-primary-700">{formMessage}</p>
          )}

          <Button type="submit" className="w-full" disabled={submitting}>
            {submitting ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> : null}
            {activeTab === "sign-in" ? t("signInTab") : t("createAccount")}
          </Button>
        </form>

        <div className="relative my-5 flex items-center">
          <div className="flex-grow border-t border-gray-100" />
          <span className="mx-3 text-xs text-neutral-400">{t("orContinueWith")}</span>
          <div className="flex-grow border-t border-gray-100" />
        </div>
        <button
          type="button"
          onClick={googleSignIn}
          className="flex w-full items-center justify-center gap-2 rounded-lg border border-gray-200 bg-white px-3 py-2.5 text-sm font-medium text-neutral-700 transition-colors hover:bg-neutral-50"
        >
          <svg className="h-4 w-4" viewBox="0 0 24 24" aria-hidden>
            <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.27-4.74 3.27-8.1Z" />
            <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84A11 11 0 0 0 12 23Z" />
            <path fill="#FBBC05" d="M5.84 14.1a6.6 6.6 0 0 1 0-4.2V7.06H2.18a11 11 0 0 0 0 9.88l3.66-2.84Z" />
            <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1A11 11 0 0 0 2.18 7.06l3.66 2.84C6.71 7.31 9.14 5.38 12 5.38Z" />
          </svg>
          {t("continueWithGoogle")}
        </button>
      </div>

      <p className="mt-6 text-center text-xs text-neutral-500">
        {t.rich("legalNotice", {
          terms: (chunks) => (
            <Link href="/terms" className="text-primary-600 hover:underline">
              {chunks}
            </Link>
          ),
          privacy: (chunks) => (
            <Link href="/privacy" className="text-primary-600 hover:underline">
              {chunks}
            </Link>
          ),
        })}
      </p>
    </div>
  );
}
