"use client";

import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useEffect, useMemo, useState } from "react";

import { safeNextUrl } from "@/lib/auth-navigation";
import {
  clearAccessToken,
  getAccessToken,
  getMe,
  getWebApiBaseUrl,
  loginWithPassword,
  type WebAuthNormalizedError,
} from "@/lib/web-auth-client";

function friendlyAuthMessage(err: WebAuthNormalizedError): string {
  if (err.status === 401) return "Email hoặc mật khẩu không đúng.";
  if (err.code === "NO_TOKEN") return "Phiên không hợp lệ. Vui lòng thử lại.";
  return err.message || "Đã có lỗi xảy ra.";
}

/** Never surface stack traces or non-serializable error payloads in the UI. */
function toSafeAuthError(caught: unknown): WebAuthNormalizedError {
  if (caught && typeof caught === "object") {
    const o = caught as Record<string, unknown>;
    if (typeof o.message === "string" || typeof o.status === "number" || typeof o.code === "string") {
      const message =
        typeof o.message === "string" && o.message.length > 0 ? o.message : "Đã có lỗi xảy ra.";
      const status = typeof o.status === "number" ? o.status : undefined;
      const code = typeof o.code === "string" ? o.code : undefined;
      return { message, status, code };
    }
  }
  if (caught instanceof Error && typeof caught.message === "string" && caught.message.length > 0) {
    return { message: caught.message };
  }
  return { message: "Đã có lỗi xảy ra." };
}

function googleOAuthReturnMessage(code: string | null): string | null {
  if (!code) return null;
  switch (code) {
    case "GOOGLE_EMAIL_CONFLICT":
      return "Email Google trùng với tài khoản đã đăng ký bằng mật khẩu. Hãy đăng nhập bằng mật khẩu hoặc dùng email Google khác.";
    case "GOOGLE_ACCESS_DENIED":
      return "Bạn đã hủy đăng nhập Google.";
    case "GOOGLE_OAUTH_STATE":
      return "Phiên đăng nhập Google không hợp lệ hoặc đã hết hạn. Vui lòng thử lại.";
    case "GOOGLE_NOT_CONFIGURED":
      return "Đăng nhập Google chưa được cấu hình trên máy chủ. Vui lòng thử lại sau.";
    case "GOOGLE_OAUTH_FAILED":
    default:
      return "Đăng nhập Google không thành công. Vui lòng thử lại.";
  }
}

function LoginFormInner() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const nextRaw = searchParams.get("next");
  const nextDest = safeNextUrl(nextRaw, "/");
  const oauthReturnError = useMemo(() => googleOAuthReturnMessage(searchParams.get("auth_error")), [searchParams]);

  useEffect(() => {
    if (searchParams.get("auth_error")) {
      clearAccessToken();
    }
  }, [searchParams]);

  useEffect(() => {
    let alive = true;
    (async () => {
      if (!getAccessToken()) return;
      try {
        const { user } = await getMe();
        if (!alive) return;
        if (user.requiresPhoneVerification) {
          router.replace(`/verify-phone?next=${encodeURIComponent(nextDest)}`);
        } else {
          router.replace(nextDest);
        }
      } catch {
        /* expired or invalid token — stay on login */
      }
    })();
    return () => {
      alive = false;
    };
  }, [router, nextDest]);

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    const em = email.trim();
    if (!em) {
      setError("Vui lòng nhập email.");
      return;
    }
    if (!password) {
      setError("Vui lòng nhập mật khẩu.");
      return;
    }
    setLoading(true);
    try {
      await loginWithPassword(em, password);
      const { user } = await getMe();
      if (user.requiresPhoneVerification) {
        router.replace(`/verify-phone?next=${encodeURIComponent(nextDest)}`);
      } else {
        router.replace(nextDest);
      }
    } catch (caught: unknown) {
      setError(friendlyAuthMessage(toSafeAuthError(caught)));
    } finally {
      setLoading(false);
    }
  }

  const bannerError = error ?? oauthReturnError;

  return (
    <form onSubmit={onSubmit} className="mt-10 space-y-5">
      {bannerError ? (
        <p
          className="rounded-lg border border-red-900/40 bg-red-950/25 px-3 py-2 text-sm text-red-200/90"
          role="alert"
        >
          {bannerError}
        </p>
      ) : null}
      <div>
        <label htmlFor="login-email" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
          Email
        </label>
        <input
          id="login-email"
          name="email"
          type="email"
          autoComplete="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          className="mt-1.5 w-full rounded-lg border border-stone-800/80 bg-black/30 px-3 py-2.5 text-[15px] text-stone-100 outline-none ring-amber-900/25 focus:ring-2"
        />
      </div>
      <div>
        <label htmlFor="login-password" className="block text-xs font-medium uppercase tracking-wider text-stone-500">
          Mật khẩu
        </label>
        <input
          id="login-password"
          name="password"
          type="password"
          autoComplete="current-password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          className="mt-1.5 w-full rounded-lg border border-stone-800/80 bg-black/30 px-3 py-2.5 text-[15px] text-stone-100 outline-none ring-amber-900/25 focus:ring-2"
        />
      </div>
      <button
        type="submit"
        disabled={loading}
        className="mt-2 w-full rounded-xl border border-amber-700/45 bg-amber-950/45 py-3 text-sm font-medium text-amber-50/95 transition hover:bg-amber-950/65 disabled:cursor-not-allowed disabled:opacity-50"
      >
        {loading ? "Đang đăng nhập…" : "Đăng nhập"}
      </button>
      <button
        type="button"
        className="w-full rounded-xl border border-stone-700/55 bg-stone-900/40 py-2.5 text-sm font-medium text-stone-200/95 transition hover:bg-stone-900/65"
        onClick={() => {
          window.location.href = `${getWebApiBaseUrl()}/auth/google`;
        }}
      >
        Đăng nhập Google
      </button>
      <p className="text-center text-xs leading-relaxed text-stone-500">
        Google login sẽ yêu cầu xác minh số điện thoại sau lần đăng nhập đầu tiên.
      </p>
      <p className="text-center text-sm text-stone-500">
        Chưa có tài khoản?{" "}
        <Link href="/register" className="ctkp-text-link">
          Đăng ký
        </Link>
      </p>
    </form>
  );
}

export default function LoginPage() {
  return (
    <main className="mx-auto max-w-[1100px] flex-1 px-4 py-16 sm:px-8 sm:py-20">
      <article className="mx-auto max-w-md">
        <header className="text-center">
          <div className="ctkp-rule mx-auto mb-8 w-20 opacity-80" aria-hidden />
          <p className="ctkp-eyebrow tracking-[0.36em]">Cổ Thư Kỳ Tịch · đăng nhập</p>
          <h1 className="font-ctkp-display mt-5 text-[1.85rem] font-semibold leading-tight tracking-tight text-stone-100 sm:text-[2rem]">
            Đăng nhập
          </h1>
          <p className="mt-3 text-sm leading-relaxed text-stone-500">
            Một tài khoản cho beta — chậm rãi, không vội.
          </p>
        </header>
        <Suspense
          fallback={
            <p className="mt-10 text-center text-sm text-stone-500" role="status">
              Đang tải…
            </p>
          }
        >
          <LoginFormInner />
        </Suspense>
        <p className="mt-10 text-center">
          <Link href="/" className="ctkp-text-link text-sm">
            ← Về trang chủ
          </Link>
        </p>
      </article>
    </main>
  );
}
