import { ShellPage } from "@/components/page-templates";
import { Button, SectionCard } from "@/components/ui";
import { redirect } from "next/navigation";

import { getSession } from "@/lib/auth";
import { updateMyProfile } from "@/lib/admin-crud";

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

  const params = await (searchParams ?? Promise.resolve({ error: undefined }));
  const message = params.error === "missing_fullname" ? "Nama lengkap wajib diisi." : null;

  const shell = session.role === "agent" ? "agent" : session.role === "super_admin" ? "super-admin" : "admin";

  return (
    <ShellPage shell={shell} title="Edit Profile" description="Edit identitas dasar pengguna.">
      <SectionCard title="Profile form">
        <form action={updateMyProfile} className="grid gap-4 md:max-w-xl">
          {message ? <p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-sm text-warning">{message}</p> : null}
          <input
            className="rounded-xl border border-line px-4 py-3"
            defaultValue={session?.fullName ?? ""}
            placeholder="Full name"
            name="fullName"
            required
          />
          <input className="rounded-xl border border-line px-4 py-3" placeholder="Avatar URL" name="avatarUrl" />
          <div>
            <Button type="submit">Save changes</Button>
          </div>
        </form>
      </SectionCard>
    </ShellPage>
  );
}
