import { redirect } from "next/navigation";

import { ShellPage } from "@/components/page-templates";
import { Button, SectionCard } from "@/components/ui";
import { getSession } from "@/lib/auth";
import { createTeamUser } from "@/lib/admin-crud";
import { prisma } from "@/lib/prisma";

export default async function NewUserPage({
  searchParams
}: {
  searchParams?: Promise<{ error?: string }>; 
}) {
  const params = await (searchParams ?? Promise.resolve({ error: undefined }));
  const session = await getSession();
  if (!session) {
    redirect("/login");
  }

  const roles = await prisma.role.findMany({
    where: { tenantId: session.tenantId, code: { in: ["ADMIN_CLIENT", "AGENT"] } },
    orderBy: { code: "asc" }
  });
  const error = params?.error;
  const errorMessage = error === "missing_fields" ? "Lengkapi nama, email, dan role." : error === "invalid_role" ? "Role tidak valid." : null;

  return (
    <ShellPage shell="admin" title="Create User" description="Tambah admin client atau agent baru.">
      <SectionCard title="User form">
        <form action={createTeamUser} className="grid gap-4 md:max-w-2xl">
          {errorMessage ? <p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-sm text-warning">{errorMessage}</p> : null}
          <input name="fullName" required placeholder="Full name" className="rounded-xl border border-line px-4 py-3" />
          <input name="email" required type="email" placeholder="Email" className="rounded-xl border border-line px-4 py-3" />
          <label className="md:col-span-2 block text-sm">
            <span className="text-on-surface-variant">Role</span>
            <select name="roleId" required className="mt-2 w-full rounded-xl border border-line px-4 py-3">
              <option value="">Pilih role</option>
              {roles.map((role) => (
                <option key={role.id} value={role.id}>
                  {role.name}
                </option>
              ))}
            </select>
          </label>
          <label className="md:col-span-2 block text-sm">
            <span className="text-on-surface-variant">Status</span>
            <select name="status" defaultValue="INVITED" className="mt-2 w-full rounded-xl border border-line px-4 py-3">
              <option value="INVITED">Invited</option>
              <option value="ACTIVE">Active</option>
              <option value="DISABLED">Disabled</option>
            </select>
          </label>
          <input
            name="password"
            type="password"
            placeholder="Password (wajib untuk status Active)"
            className="md:col-span-2 rounded-xl border border-line px-4 py-3"
          />
          <Button type="submit" className="md:col-span-2 w-full">
            Save user
          </Button>
        </form>
      </SectionCard>
    </ShellPage>
  );
}
