import { ShellPage } from "@/components/page-templates";
import { Button, SectionCard } from "@/components/ui";
import { getSession } from "@/lib/auth";
import { changePassword } from "@/lib/admin-crud";
import { redirect } from "next/navigation";

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

  const params = await (searchParams ?? Promise.resolve({ error: undefined, success: undefined }));
  const shell = session.role === "agent" ? "agent" : session.role === "super_admin" ? "super-admin" : "admin";
  const infoMessage =
    params.success === "updated"
      ? "Password berhasil diperbarui."
      : params.error === "missing_fields"
        ? "Lengkapi semua field password."
        : params.error === "password_mismatch"
          ? "Password baru dan konfirmasi tidak sama."
          : params.error === "wrong_current_password"
            ? "Password lama tidak sesuai."
            : null;

  return (
    <ShellPage shell={shell} title="Change Password" description="Ubah password akun Anda.">
      <SectionCard title="Password form">
        <form action={changePassword} className="grid gap-4 md:max-w-xl">
          {infoMessage ? <p className="rounded-xl border border-success/30 bg-success/10 p-3 text-sm text-success">{infoMessage}</p> : null}
          <input type="password" name="currentPassword" className="rounded-xl border border-line px-4 py-3" placeholder="Current password" />
          <input type="password" name="newPassword" className="rounded-xl border border-line px-4 py-3" placeholder="New password" />
          <input
            type="password"
            name="confirmPassword"
            className="rounded-xl border border-line px-4 py-3"
            placeholder="Confirm new password"
          />
          <div>
            <Button type="submit">Update password</Button>
          </div>
        </form>
      </SectionCard>
    </ShellPage>
  );
}
