import { prisma } from "@/lib/prisma";
import { formatDate } from "@/lib/format";
import CustomersTabs from "@/components/admin/CustomersTabs";
import ScrollableTable from "@/components/admin/ScrollableTable";

export default async function AdminCustomerAddressesPage() {
  const orders = await prisma.order.findMany({
    select: {
      customerName: true,
      email: true,
      phone: true,
      addressLine1: true,
      addressLine2: true,
      city: true,
      state: true,
      pincode: true,
      createdAt: true,
    },
    orderBy: { createdAt: "desc" },
  });

  type AddressRow = {
    key: string;
    customerName: string;
    email: string;
    phone: string;
    address: string;
    city: string;
    state: string;
    pincode: string;
    lastUsed: Date;
  };

  const seen = new Map<string, AddressRow>();
  for (const o of orders) {
    const address = [o.addressLine1, o.addressLine2].filter(Boolean).join(", ");
    const key = `${o.email}|${address}|${o.city}|${o.pincode}`;
    if (!seen.has(key)) {
      seen.set(key, {
        key,
        customerName: o.customerName,
        email: o.email,
        phone: o.phone,
        address,
        city: o.city,
        state: o.state,
        pincode: o.pincode,
        lastUsed: o.createdAt,
      });
    }
  }
  const rows = [...seen.values()];

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Customer Addresses</h1>
      <p className="mt-1 text-sm text-stone-500">
        Every distinct shipping address used at checkout, most recent first. There&apos;s no separate saved-address book yet — this is drawn from order history.
      </p>

      <CustomersTabs active="/iv-manage-84x2/customers/addresses" />

      {rows.length === 0 ? (
        <p className="rounded-lg border border-rose-100 bg-white p-4 text-sm text-stone-500">No addresses yet.</p>
      ) : (
        <ScrollableTable>
          <table className="w-full min-w-[900px] text-sm">
            <thead className="sticky top-0 z-10 bg-rose-50 text-left text-xs uppercase text-stone-500">
              <tr>
                <th className="p-3">Customer</th>
                <th className="p-3">Phone</th>
                <th className="p-3">Address</th>
                <th className="p-3">City</th>
                <th className="p-3">State</th>
                <th className="p-3">Pincode</th>
                <th className="p-3">Last used</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {rows.map((r) => (
                <tr key={r.key}>
                  <td className="whitespace-nowrap p-3">
                    <p className="font-medium text-stone-800">{r.customerName}</p>
                    <p className="text-xs text-stone-500">{r.email}</p>
                  </td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{r.phone}</td>
                  <td className="p-3 text-stone-600">{r.address}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{r.city}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{r.state}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{r.pincode}</td>
                  <td className="whitespace-nowrap p-3 text-stone-500">{formatDate(r.lastUsed)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </ScrollableTable>
      )}
    </div>
  );
}
