import { redirect } from "next/navigation";
import Link from "next/link";
import { getCurrentUser } from "@/lib/auth";
import { loginAction } from "@/app/login/actions";

const inputCls =
  "w-full rounded-md border border-neutral-300 dark:border-neutral-700 bg-white dark:bg-neutral-900 px-3 py-2 text-sm text-neutral-900 dark:text-neutral-200 focus:border-neutral-500 focus:dark:border-neutral-400 focus:outline-none";

export default async function LoginPage(props: PageProps<"/login">) {
  const sp = await props.searchParams;
  const next = typeof sp.next === "string" ? sp.next : "/dashboard";
  const hasError = sp.error === "1";

  const user = await getCurrentUser();
  if (user) redirect(next);

  return (
    <div className="mx-auto max-w-sm space-y-6">
      <h1 className="text-2xl font-semibold">Log In</h1>
      {hasError && (
        <p className="rounded-md border border-red-300 dark:border-red-700 bg-red-50 dark:bg-red-950 px-3 py-2 text-sm text-red-800 dark:text-red-300">
          Invalid email or password.
        </p>
      )}
      <form action={loginAction} className="space-y-3">
        <input type="hidden" name="next" value={next} />
        <div>
          <label className="mb-1 block text-sm font-medium text-neutral-800 dark:text-neutral-300">Email</label>
          <input type="email" name="email" required autoFocus className={inputCls} />
        </div>
        <div>
          <label className="mb-1 block text-sm font-medium text-neutral-800 dark:text-neutral-300">Password</label>
          <input type="password" name="password" required className={inputCls} />
        </div>
        <button type="submit" className="w-full rounded-md bg-neutral-900 dark:bg-neutral-100 dark:text-neutral-900 px-4 py-2 text-sm font-medium text-white hover:bg-neutral-800 dark:hover:bg-neutral-200">
          Log In
        </button>
      </form>
      <p className="text-sm text-neutral-600 dark:text-neutral-400">
        You can browse horse profiles without logging in. Log in to edit records or manage the farm.
      </p>
      <p className="text-sm text-neutral-600 dark:text-neutral-400">
        New breeder? <Link href="/register" className="underline">Register an account</Link>
      </p>
    </div>
  );
}
