import { prisma } from "@/lib/prisma";
import { formatPaise, formatDate } from "@/lib/format";
import { createCoupon, toggleCoupon, deleteCoupon } from "@/lib/actions/discounts";
import DiscountsTabs from "@/components/admin/DiscountsTabs";

export default async function AdminCouponsPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const { error } = await searchParams;
  const coupons = await prisma.coupon.findMany({ orderBy: { createdAt: "desc" } });

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Coupon Codes</h1>
      <p className="mt-1 text-sm text-stone-500">
        Codes customers enter at checkout for a percent or flat discount. Only one of a coupon or an active Festival Offer applies per order — whichever gives the bigger discount.
      </p>

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

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

      <form action={createCoupon} className="grid max-w-3xl grid-cols-2 gap-3 rounded-lg border border-rose-100 bg-white p-4 sm:grid-cols-5">
        <input name="code" required placeholder="CODE (e.g. WELCOME10)" className="rounded-md border border-stone-300 px-2 py-2 text-sm uppercase sm:col-span-2" />
        <select name="type" className="rounded-md border border-stone-300 px-2 py-2 text-sm">
          <option value="percent">% off</option>
          <option value="flat">₹ off</option>
        </select>
        <input name="value" type="number" min={1} step="0.01" required placeholder="Value" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
        <input name="minOrderValue" type="number" min={0} step="0.01" placeholder="Min order ₹ (optional)" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
        <input name="maxUses" type="number" min={1} placeholder="Max uses (optional)" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
        <input name="expiresAt" type="date" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
        <label className="flex items-center gap-2 text-sm text-stone-600 sm:col-span-2">
          <input type="checkbox" name="oneUsePerCustomer" className="rounded border-stone-300" />
          One use per customer
        </label>
        <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-1">
          Add coupon
        </button>
      </form>

      <div className="mt-8 overflow-hidden rounded-lg border border-rose-100 bg-white">
        {coupons.length === 0 ? (
          <p className="p-4 text-sm text-stone-500">No coupons 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">Code</th>
                <th className="p-3">Discount</th>
                <th className="p-3">Min order</th>
                <th className="p-3">Uses</th>
                <th className="p-3">Expires</th>
                <th className="p-3">Status</th>
                <th className="p-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {coupons.map((c) => (
                <tr key={c.id}>
                  <td className="p-3 font-mono font-medium text-stone-800">{c.code}</td>
                  <td className="p-3 text-stone-600">{c.type === "percent" ? `${c.value}% off` : `${formatPaise(c.value)} off`}</td>
                  <td className="p-3 text-stone-600">{c.minOrderValue ? formatPaise(c.minOrderValue) : "—"}</td>
                  <td className="p-3 text-stone-600">
                    {c.usedCount}
                    {c.maxUses ? ` / ${c.maxUses}` : ""}
                    {c.oneUsePerCustomer && <span className="ml-1.5 rounded-full bg-gold-50 px-1.5 py-0.5 text-[10px] font-medium text-gold-600">1/customer</span>}
                  </td>
                  <td className="p-3 text-stone-500">{c.expiresAt ? formatDate(c.expiresAt) : "—"}</td>
                  <td className="p-3">
                    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${c.active ? "bg-emerald-100 text-emerald-800" : "bg-stone-200 text-stone-600"}`}>
                      {c.active ? "Active" : "Inactive"}
                    </span>
                  </td>
                  <td className="p-3 text-right">
                    <div className="flex items-center justify-end gap-3">
                      <form action={toggleCoupon.bind(null, c.id)}>
                        <button type="submit" className="text-xs text-stone-500 hover:text-rose-700">
                          {c.active ? "Deactivate" : "Activate"}
                        </button>
                      </form>
                      <form action={deleteCoupon.bind(null, c.id)}>
                        <button type="submit" className="text-xs text-stone-400 hover:text-red-700">
                          Delete
                        </button>
                      </form>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
