import { redirect } from "next/navigation";
import { Card, CardContent, CardDescription, CardHeader, CardTitle, CardFooter } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { db } from "@/db/client";
import { adminUsers } from "@/db/schema";
import { createSession, hasAnyAdmin } from "@/lib/auth";
import { hashPassword } from "@/lib/password";

export const metadata = { title: "系统管理员注册" };

async function signUpAction(formData: FormData) {
  "use server";
  const name = String(formData.get("name") || "").trim();
  const email = String(formData.get("email") || "").trim();
  const password = String(formData.get("password") || "");
  const confirm = String(formData.get("confirm") || "");

  if (!name || !email || !password) return;
  if (password !== confirm) return;

  // 仅在没有任何管理员时，允许注册首个系统管理员
  const any = await hasAnyAdmin();
  if (any) {
    redirect("/signin");
  }
  const passwordHash = await hashPassword(password);
  const [row] = await db
    .insert(adminUsers)
    .values({ name, email, passwordHash, role: 'super' })
    .returning({ id: adminUsers.id });
  await createSession(row.id);
  redirect("/books");
}

export default async function SignUpPage() {
  // 如已有管理员，禁止再注册系统管理员
  const any = await hasAnyAdmin();
  if (any) redirect("/signin");
  return (
    <div className="flex min-h-screen items-center justify-center bg-gray-50 p-4">
      <Card className="w-full max-w-md">
        <CardHeader>
          <CardTitle>系统管理员注册</CardTitle>
          <CardDescription>创建系统管理员账号</CardDescription>
        </CardHeader>
        <CardContent>
          <form action={signUpAction} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="name">姓名</Label>
              <Input id="name" name="name" placeholder="张三" required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="email">邮箱</Label>
              <Input id="email" name="email" type="email" placeholder="admin@example.com" required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="password">密码</Label>
              <Input id="password" name="password" type="password" required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="confirm">确认密码</Label>
              <Input id="confirm" name="confirm" type="password" required />
            </div>
            <Button type="submit" className="w-full">注册</Button>
          </form>
        </CardContent>
        <CardFooter>
          <a href="/signin" className="text-sm text-blue-600 hover:underline">已有账号？去登录</a>
        </CardFooter>
      </Card>
    </div>
  );
}
