import { prisma } from "@/lib/prisma";
import { createCustomerGroup, deleteCustomerGroup } from "@/lib/actions/customers";
import CustomersTabs from "@/components/admin/CustomersTabs";

export default async function AdminCustomerGroupsPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const { error } = await searchParams;
  const groups = await prisma.customerGroup.findMany({
    orderBy: { name: "asc" },
    include: { _count: { select: { customers: true } } },
  });

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Customer Groups</h1>
      <p className="mt-1 text-sm text-stone-500">
        Segment customers — e.g. VIP, Wholesale, Regular — to make it easier to target them later (discounts, marketing).
      </p>

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

      {error && <p className="mb-4 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      <form action={createCustomerGroup} className="flex max-w-md gap-2">
        <input
          type="text"
          name="name"
          required
          placeholder="New group name (e.g. VIP)"
          className="flex-1 rounded-md border border-stone-300 px-3 py-2 text-sm"
        />
        <button type="submit" className="rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800">
          Add
        </button>
      </form>

      <div className="mt-6 overflow-hidden rounded-lg border border-rose-100 bg-white">
        {groups.length === 0 ? (
          <p className="p-4 text-sm text-stone-500">No groups yet.</p>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-rose-50/60 text-left text-xs uppercase text-stone-500">
              <tr>
                <th className="p-3">Name</th>
                <th className="p-3">Customers</th>
                <th className="p-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {groups.map((g) => (
                <tr key={g.id}>
                  <td className="p-3 font-medium text-stone-800">{g.name}</td>
                  <td className="p-3 text-stone-500">{g._count.customers}</td>
                  <td className="p-3 text-right">
                    <form action={deleteCustomerGroup.bind(null, g.id)}>
                      <button type="submit" className="text-xs text-stone-400 hover:text-red-700">
                        Delete
                      </button>
                    </form>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
