import Link from "next/link";
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth/auth-options";
import { AuthLayoutShell } from "@/components/features/auth/AuthLayoutShell";
import { LoginForm } from "@/components/features/auth/LoginForm";
import { getValidatedPostAuthPath } from "@/lib/auth/post-auth-path";
import { Suspense } from "react";

export default async function LoginPage({
  searchParams,
}: {
  searchParams?: Record<string, string | string[] | undefined>;
}) {
  const errorParam = searchParams?.error;
  const error =
    typeof errorParam === "string"
      ? errorParam
      : Array.isArray(errorParam)
        ? errorParam[0]
        : undefined;

  const session = await getServerSession(authOptions);
  if (session?.user?.id) {
    const landing = await getValidatedPostAuthPath(session.user.id);
    if (landing) {
      redirect(landing);
    }
    // Stale JWT (inactive user / suspended workspace / DB mismatch).
    // Clear cookie so we never bounce login ↔ dashboard.
    if (!error) {
      redirect(
        `/api/auth/force-logout?callbackUrl=${encodeURIComponent("/login?error=SessionExpired")}`
      );
    }
  }

  const message =
    error === "maintenance" || error === "Maintenance"
      ? "The platform is in maintenance mode. Please try again later."
      : error === "WorkspaceUnavailable"
        ? "Your workspace is unavailable. Contact support."
        : error === "AccountInactive"
          ? "This account is inactive."
          : error === "DatabaseError"
            ? "We could not verify your session. Please sign in again."
            : null;

  return (
    <AuthLayoutShell>
      <div className="mb-[26px] flex rounded-[9px] bg-[#F1F5F9] p-1">
        <span className="flex-1 rounded-md bg-white py-2 text-center text-[13.5px] font-semibold text-primary shadow">
          Log in
        </span>
        <Link
          href="/register"
          className="flex-1 py-2 text-center text-[13.5px] font-semibold text-muted hover:text-text"
        >
          Register
        </Link>
      </div>
      {message && (
        <p className="mb-4 rounded-lg border border-warning/30 bg-warning-bg px-3 py-2 text-[13px] text-warning">
          {message}
        </p>
      )}
      <Suspense>
        <LoginForm />
      </Suspense>
    </AuthLayoutShell>
  );
}
