import { prisma } from "@/lib/prisma";
import { createBulkTier, toggleBulkTier, deleteBulkTier } from "@/lib/actions/discounts";
import DiscountsTabs from "@/components/admin/DiscountsTabs";

export default async function AdminBulkDiscountsPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const { error } = await searchParams;
  const [tiers, products, categories] = await Promise.all([
    prisma.bulkDiscountTier.findMany({ include: { product: true, category: true }, orderBy: { minQty: "asc" } }),
    prisma.product.findMany({ select: { id: true, name: true }, orderBy: { name: "asc" } }),
    prisma.category.findMany({ select: { id: true, name: true }, orderBy: { name: "asc" } }),
  ]);

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Bulk Order Discounts</h1>
      <p className="mt-1 text-sm text-stone-500">
        Quantity price breaks — e.g. buy 50+ of a product and pay 10% less per unit. Great fit for your MOQ-heavy return-gift orders.
      </p>

      <DiscountsTabs active="/iv-manage-84x2/discounts/bulk" />

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

      <form action={createBulkTier} className="grid max-w-2xl grid-cols-2 gap-3 rounded-lg border border-rose-100 bg-white p-4 sm:grid-cols-4">
        <select name="target" required className="rounded-md border border-stone-300 px-2 py-2 text-sm sm:col-span-2">
          <option value="">Applies to…</option>
          <optgroup label="Product">
            {products.map((p) => (
              <option key={p.id} value={`product:${p.id}`}>
                {p.name}
              </option>
            ))}
          </optgroup>
          <optgroup label="Category">
            {categories.map((c) => (
              <option key={c.id} value={`category:${c.id}`}>
                {c.name}
              </option>
            ))}
          </optgroup>
        </select>
        <input name="minQty" type="number" min={2} required placeholder="Min quantity" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
        <input name="discountPercent" type="number" min={1} max={90} required placeholder="% off" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
        <button type="submit" className="col-span-2 rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800 sm:col-span-4">
          Add tier
        </button>
      </form>

      <div className="mt-8 overflow-hidden rounded-lg border border-rose-100 bg-white">
        {tiers.length === 0 ? (
          <p className="p-4 text-sm text-stone-500">No bulk tiers 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">Applies to</th>
                <th className="p-3">Min qty</th>
                <th className="p-3">Discount</th>
                <th className="p-3">Status</th>
                <th className="p-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {tiers.map((t) => (
                <tr key={t.id}>
                  <td className="p-3 font-medium text-stone-800">{t.product?.name ?? t.category?.name ?? "—"}</td>
                  <td className="p-3 text-stone-600">{t.minQty}+</td>
                  <td className="p-3 text-stone-600">{t.discountPercent}% off</td>
                  <td className="p-3">
                    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${t.active ? "bg-emerald-100 text-emerald-800" : "bg-stone-200 text-stone-600"}`}>
                      {t.active ? "Active" : "Inactive"}
                    </span>
                  </td>
                  <td className="p-3 text-right">
                    <div className="flex items-center justify-end gap-3">
                      <form action={toggleBulkTier.bind(null, t.id)}>
                        <button type="submit" className="text-xs text-stone-500 hover:text-rose-700">
                          {t.active ? "Deactivate" : "Activate"}
                        </button>
                      </form>
                      <form action={deleteBulkTier.bind(null, t.id)}>
                        <button type="submit" className="text-xs text-stone-400 hover:text-red-700">
                          Delete
                        </button>
                      </form>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
