import { redirect } from "next/navigation";

import { auth } from "@/auth";
import { Button } from "@/components/ui/button";

import { loginAction } from "./actions";

type LoginPageProps = {
  searchParams: Promise<{
    callbackUrl?: string;
    error?: string;
  }>;
};

export default async function LoginPage({ searchParams }: LoginPageProps) {
  const session = await auth();

  if (session) {
    redirect("/");
  }

  const params = await searchParams;
  const callbackUrl = params.callbackUrl ?? "/";
  const hasError = params.error === "CredentialsSignin";

  return (
    <main className="flex min-h-screen items-center justify-center bg-muted px-6 py-10">
      <section className="w-full max-w-md rounded-lg border bg-background p-8 shadow-sm">
        <div className="mb-8">
          <h1 className="text-2xl font-semibold tracking-normal">
            choco-admin
          </h1>
          <p className="mt-2 text-sm text-muted-foreground">관리자 로그인</p>
        </div>

        {hasError ? (
          <div className="mb-5 rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
            관리자 아이디 또는 암호가 올바르지 않습니다.
          </div>
        ) : null}

        <form action={loginAction} className="space-y-5">
          <input name="callbackUrl" type="hidden" value={callbackUrl} />

          <div className="space-y-2">
            <label className="text-sm font-medium" htmlFor="adminName">
              관리자 아이디
            </label>
            <input
              autoComplete="username"
              autoFocus
              className="h-10 w-full rounded-md border bg-background px-3 text-sm outline-none transition-colors focus:border-ring focus:ring-3 focus:ring-ring/30"
              id="adminName"
              name="adminName"
              required
              type="text"
            />
          </div>

          <div className="space-y-2">
            <label className="text-sm font-medium" htmlFor="password">
              암호
            </label>
            <input
              autoComplete="current-password"
              className="h-10 w-full rounded-md border bg-background px-3 text-sm outline-none transition-colors focus:border-ring focus:ring-3 focus:ring-ring/30"
              id="password"
              name="password"
              required
              type="password"
            />
          </div>

          <Button className="w-full" type="submit">
            로그인
          </Button>
        </form>
      </section>
    </main>
  );
}
