import { redirect } from "next/navigation";
import { getCurrentCustomerId } from "@/lib/customer-auth";
import { prisma } from "@/lib/prisma";
import { updateProfile } from "@/lib/actions/customer-account";

export const metadata = { title: "My Profile — Iniyaval Return Gifts" };

export default async function ProfilePage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const customerId = await getCurrentCustomerId();
  if (!customerId) redirect("/account/login");

  const customer = await prisma.customer.findUnique({ where: { id: customerId } });
  if (!customer) redirect("/account/login");
  const { error } = await searchParams;

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-rose-800">Profile</h1>

      {error && <p className="mt-4 rounded-md bg-red-50 px-3 py-2 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      <form action={updateProfile} className="mt-4 max-w-md space-y-4 rounded-lg border border-rose-100 bg-white p-4">
        <div>
          <label className="text-xs text-stone-500">Email</label>
          <input type="email" value={customer.email} disabled className="mt-1 block w-full rounded-md border border-stone-200 bg-stone-50 px-3 py-2 text-sm text-stone-400" />
        </div>
        <div>
          <label className="text-xs text-stone-500">Name</label>
          <input name="name" defaultValue={customer.name ?? ""} className="mt-1 block w-full rounded-md border border-stone-300 px-3 py-2 text-sm" />
        </div>
        <div>
          <label className="text-xs text-stone-500">Phone</label>
          <input
            name="phone"
            type="tel"
            inputMode="numeric"
            pattern="\d{10}"
            maxLength={10}
            title="Enter a 10-digit mobile number"
            defaultValue={customer.phone ?? ""}
            className="mt-1 block w-full rounded-md border border-stone-300 px-3 py-2 text-sm"
          />
        </div>
        <button type="submit" className="rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800">
          Save
        </button>
      </form>
    </div>
  );
}
