import { signIn } from "@/auth";

export const metadata = { title: "Sign in — TouchBase" };

async function requestMagicLink(formData: FormData) {
  "use server";
  const email = String(formData.get("email") ?? "").trim();
  if (!email) return;
  // signIn with redirectTo handles the redirect to /login/check-email itself
  // (configured as `pages.verifyRequest` in src/auth.ts).
  await signIn("nodemailer", { email, redirectTo: "/admin" });
}

export default function LoginPage() {
  return (
    <main className="mx-auto flex min-h-full max-w-sm flex-col justify-center gap-6 p-8">
      <h1 className="text-2xl font-semibold tracking-tight">Sign in</h1>
      <p className="text-sm text-zinc-600 dark:text-zinc-400">
        Enter your email and we&apos;ll send you a sign-in link.
      </p>
      <form action={requestMagicLink} className="flex flex-col gap-3">
        <label htmlFor="email" className="text-sm font-medium">
          Email
        </label>
        <input
          id="email"
          name="email"
          type="email"
          autoComplete="email"
          required
          placeholder="you@touchbase.local"
          className="rounded-md border border-zinc-300 bg-white px-3 py-2 text-sm shadow-sm placeholder:text-zinc-400 focus:border-zinc-500 focus:outline-none focus:ring-1 focus:ring-zinc-500 dark:border-zinc-700 dark:bg-zinc-900"
        />
        <button
          type="submit"
          className="mt-2 rounded-md bg-zinc-900 px-3 py-2 text-sm font-medium text-white hover:bg-zinc-800 dark:bg-zinc-100 dark:text-zinc-900"
        >
          Send sign-in link
        </button>
      </form>
    </main>
  );
}
