"use client";

import { Suspense, useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { LoginForm } from "./login-form";

const hasKeycloak = !!process.env.AUTH_KEYCLOAK_ISSUER;

function LoginPageContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const callbackUrl = searchParams.get("callbackUrl");
  const error = searchParams.get("error");

  useEffect(() => {
    // If not an OAuth callback, redirect to home with login modal open
    if (!callbackUrl && !error) {
      router.replace("/?login=1");
    }
  }, [callbackUrl, error, router]);

  return (
    <div className="flex min-h-screen items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100 p-4">
      <Dialog defaultOpen>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-center">登录</DialogTitle>
          </DialogHeader>
          <Suspense fallback={<div>加载中...</div>}>
            <LoginForm hasKeycloak={hasKeycloak} />
          </Suspense>
        </DialogContent>
      </Dialog>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense fallback={<div className="flex min-h-screen items-center justify-center">加载中...</div>}>
      <LoginPageContent />
    </Suspense>
  );
}
