import { redirect } from "next/navigation";
import { sql } from "drizzle-orm";
import { db } from "@/db";
import { adminUsers } from "@/db/schema";
import { getAdmin } from "@/lib/auth";
import { ensureSeed } from "@/lib/data";
import { Logo } from "@/components/Logo";
import { adminLogin, setupAdmin } from "@/app/admin/actions";

export const metadata = { title: "Admin Login", robots: { index: false } };

export default async function Login({ searchParams }: { searchParams: Promise<{ err?: string }> }) {
  await ensureSeed();
  if (await getAdmin()) redirect("/admin");
  const { err } = await searchParams;
  const [{ c }] = await db.select({ c: sql<number>`count(*)::int` }).from(adminUsers);
  const setup = c === 0;
  return (
    <div className="min-h-screen grid place-items-center bg-gradient-to-br from-mint to-softblue p-4">
      <div className="card p-8 w-full max-w-md anim-fade-up">
        <Logo />
        <h1 className="text-xl font-extrabold mt-6">{setup ? "Create the first administrator" : "Admin sign in"}</h1>
        <p className="text-sm text-slate-500 mb-6">{setup ? "No admin exists yet. This one-time setup creates the owner account." : "Secure access for authorised pharmacy staff."}</p>
        {err && <p className="text-sm bg-red-50 text-red-700 rounded-lg px-3 py-2 mb-4">{err}</p>}
        <form action={setup ? setupAdmin : adminLogin} className="space-y-4">
          {setup && <input name="name" placeholder="Full name" required className="input" />}
          <input name="email" type="email" placeholder="Email" required className="input" />
          <input name="password" type="password" placeholder={setup ? "Strong password (min 10 chars)" : "Password"} required minLength={setup ? 10 : 1} className="input" />
          <button className="btn btn-green w-full">{setup ? "Create Admin & Continue" : "Sign In"}</button>
        </form>
      </div>
    </div>
  );
}
