import { redirect } from "next/navigation";
import { createClient } from "@/lib/supabase/server";
import { APP_NAME, ROUTES } from "@/lib/constants";
import { env } from "@/lib/env";
import { Card } from "@/components/ui/card";
import { LoginForm } from "@/components/forms/login-form";
import { getRegionCodes } from "@/lib/regions";
import { LocalAccessShell } from "@/components/forms/local-access-shell";

function normalizeNextPath(nextPath?: string) {
  if (!nextPath) return undefined;
  if (!nextPath.startsWith("/") || nextPath.startsWith("//")) return undefined;
  return nextPath;
}

export default async function LoginPage({
  searchParams,
}: {
  searchParams: Promise<{ next?: string; error?: string }>;
}) {
  const params = await searchParams;
  const safeNext = normalizeNextPath(params.next);

  if (env.disableAuth) {
    const scopes = getRegionCodes();
    const localError =
      params.error === "invalid-access-password"
        ? "Invalid access password."
        : params.error === "invalid-scope"
          ? "Please select a valid region."
          : params.error === "too-many-attempts"
            ? "Too many failed attempts. Please wait 15 minutes before trying again."
            : params.error
              ? "Could not set local access mode. Please try again."
              : null;

    return <LocalAccessShell scopes={scopes} error={localError} nextPath={safeNext} />;
  }

  const [, supabase] = await Promise.all([Promise.resolve(params), createClient()]);

  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (user) {
    redirect(ROUTES.dashboard);
  }

  return (
    <main className="mx-auto flex min-h-screen w-full max-w-6xl items-center justify-center p-6">
      <div className="grid w-full gap-8 lg:grid-cols-[1.2fr_0.9fr]">
        <section className="hidden rounded-3xl border border-slate-200 bg-slate-50 p-10 lg:block">
          <p className="caption text-xs uppercase tracking-[0.2em] text-[#2663AC]">Otsuka VEEVA analytics</p>
          <h1 className="mt-4 text-4xl font-semibold text-slate-900">{APP_NAME}</h1>
          <p className="mt-4 max-w-xl text-slate-600">
            Upload affiliate email exports, merge engagement progress, enrich with metadata, and keep
            country-scoped dashboards aligned with access controls.
          </p>
        </section>

        <Card className="mx-auto w-full max-w-md border-slate-300 bg-white">
          <h2 className="text-xl font-semibold">Sign in</h2>
          <p className="mt-2 text-sm text-slate-600">
            Use your Supabase Auth credentials to continue.
          </p>
          <div className="mt-6">
            <LoginForm nextPath={safeNext} />
          </div>
        </Card>
      </div>
    </main>
  );
}
