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 { LocalAccessForm } from "@/components/forms/local-access-form";

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;

  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
            ? "Could not set local access mode. Please try again."
            : null;

    return (
      <main className="mx-auto flex min-h-screen w-full max-w-5xl items-center justify-center p-6">
        <Card className="w-full max-w-4xl border-[#d2e2f4] bg-[linear-gradient(135deg,#ffffff_0%,#f3f9ff_62%,#fff4e8_100%)] p-8 md:p-10">
          <div className="flex items-center gap-2">
            <span className="h-2 w-2 rounded-full bg-[#F7993A] shadow-[0_0_10px_rgba(247,153,58,0.75)]" />
            <p className="caption text-xs uppercase tracking-[0.2em] text-[#2663AC]">Local Access Mode</p>
          </div>
          <h1 className="mt-3 text-4xl font-black tracking-tight text-slate-900 md:text-5xl">Choose Dashboard Access</h1>
          <p className="mt-3 inline-flex items-center rounded-full border border-[#f7d5b0] bg-[#fff4e8] px-3 py-1 text-xs font-semibold uppercase tracking-[0.14em] text-[#b76a24]">
            Access passwords are set per role/region in env
          </p>

          <LocalAccessForm scopes={scopes} error={localError} />
        </Card>
      </main>
    );
  }

  const [{ next }, supabase] = await Promise.all([Promise.resolve(params), createClient()]);
  const safeNext = normalizeNextPath(next);

  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>
  );
}
