import { redirect } from "next/navigation";
import { getCurrentCustomerId } from "@/lib/customer-auth";
import { prisma } from "@/lib/prisma";
import { createAddress, updateAddress, deleteAddress, setDefaultAddress } from "@/lib/actions/customer-account";
import AddressForm from "@/components/AddressForm";

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

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

  const addresses = await prisma.customerAddress.findMany({ where: { customerId }, orderBy: [{ isDefault: "desc" }, { createdAt: "asc" }] });
  const editing = edit ? addresses.find((a) => a.id === edit) : null;

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-rose-800">Manage Addresses</h1>
      <p className="mt-1 text-sm text-stone-500">Saved addresses for faster checkout.</p>

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

      <div className="mt-4 space-y-3">
        {addresses.map((a) => (
          <div key={a.id} className="rounded-lg border border-rose-100 bg-white p-4">
            {editing?.id === a.id ? (
              <AddressForm action={updateAddress.bind(null, a.id)} defaultValues={a} submitLabel="Save" cancelHref="/account/addresses" />
            ) : (
              <div className="flex items-start justify-between">
                <div className="text-sm">
                  <p className="font-medium text-stone-800">
                    {a.label && <span className="mr-2 rounded-full bg-rose-50 px-2 py-0.5 text-xs text-rose-700">{a.label}</span>}
                    {a.name}
                    {a.isDefault && <span className="ml-2 rounded-full bg-emerald-100 px-2 py-0.5 text-xs text-emerald-800">Default</span>}
                  </p>
                  <p className="mt-1 text-stone-500">
                    {a.addressLine1}
                    {a.addressLine2 ? `, ${a.addressLine2}` : ""}
                    {a.landmark ? ` (near ${a.landmark})` : ""}, {a.city}
                    {a.district ? `, ${a.district}` : ""}, {a.state} {a.pincode}
                  </p>
                  <p className="text-stone-500">{a.phone}</p>
                </div>
                <div className="flex shrink-0 flex-col items-end gap-1 text-xs">
                  <a href={`/account/addresses?edit=${a.id}`} className="font-medium text-rose-700 hover:underline">
                    Edit
                  </a>
                  {!a.isDefault && (
                    <form action={setDefaultAddress.bind(null, a.id)}>
                      <button type="submit" className="text-stone-500 hover:text-rose-700">
                        Set as default
                      </button>
                    </form>
                  )}
                  <form action={deleteAddress.bind(null, a.id)}>
                    <button type="submit" className="text-stone-400 hover:text-red-700">
                      Delete
                    </button>
                  </form>
                </div>
              </div>
            )}
          </div>
        ))}
      </div>

      <div className="mt-6 rounded-lg border border-rose-100 bg-white p-4">
        <h2 className="text-sm font-semibold text-stone-700">Add a new address</h2>
        <div className="mt-3">
          <AddressForm action={createAddress} submitLabel="Add address" />
        </div>
      </div>
    </div>
  );
}
