import Image from "next/image";
import { redirect } from "next/navigation";
import { SignInForm } from "@/features/auth/sign-in-form";
import { ThemeToggle } from "@/components/layout/theme";
import { isCsmsApiConfigured } from "@/lib/auth/server-config";
import { canRestoreExpiredSession, getServerSession } from "@/lib/auth/server-session";
import { SessionRecovery } from "@/features/auth/session-lifecycle";

export const metadata = { title: "Sign In" };
export const dynamic = "force-dynamic";

export default async function SignInPage() {
  const apiEnabled = isCsmsApiConfigured();
  const session = apiEnabled ? await getServerSession() : null;
  if (session) redirect(session.passwordSetupRequired ? "/set-password" : "/");
  const restoreSession = apiEnabled && await canRestoreExpiredSession();

  return (
    <main className="relative flex min-h-dvh">
      <section className="flex w-full items-center justify-center p-6 lg:w-1/2">
        <SessionRecovery enabled={restoreSession}>
          <SignInForm apiEnabled={apiEnabled} />
        </SessionRecovery>
      </section>
      <aside className="relative hidden min-h-dvh w-1/2 items-center justify-center overflow-hidden bg-auth-cover lg:flex">
        <Image
          src="/branding/cover.png"
          alt=""
          fill
          priority
          sizes="50vw"
          className="object-cover opacity-30"
        />
        <Image
          src="/images/shape/grid-01.svg"
          alt=""
          width={540}
          height={250}
          loading="eager"
          className="absolute right-0 top-0 h-auto w-[540px] opacity-40"
        />
        <Image
          src="/images/shape/grid-01.svg"
          alt=""
          width={540}
          height={250}
          loading="eager"
          className="absolute bottom-0 left-0 h-auto w-[540px] rotate-180 opacity-40"
        />
        <div className="relative max-w-xs text-center text-white">
          <Image
            src="/branding/tiar-icon.svg"
            alt="Tiar"
            width={200}
            height={200}
            priority
            className="mx-auto mb-2"
          />
          <h2 className="mb-4 text-2xl font-bold">Parking+</h2>
          <p className="text-base text-white/60">
            Monetization and Reporting System for Your EV Charging Stations
          </p>
        </div>
      </aside>
      <div className="fixed bottom-6 right-6 hidden sm:block">
        <ThemeToggle />
      </div>
    </main>
  );
}
