import { db } from "@/lib/db";
import { requireConfAccess } from "@/lib/rbac";
import { Card, PageHeader, btn, input, Field, Badge } from "@/components/ui";
import { fmtDate, formatMoney } from "@/lib/utils";
import { createCoupon, createTicketType, toggleCoupon, toggleTicketType } from "../actions";

export const metadata = { title: "Tickets & Coupons" };

export default async function TicketsPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  await requireConfAccess(id, "registrations.manage");
  const [tickets, coupons] = await Promise.all([
    db.ticketType.findMany({
      where: { conferenceId: id },
      orderBy: { price: "asc" },
      include: { _count: { select: { registrations: { where: { status: { not: "CANCELLED" } } } } } },
    }),
    db.coupon.findMany({ where: { conferenceId: id }, orderBy: { code: "asc" } }),
  ]);

  return (
    <main>
      <PageHeader title="Tickets & coupons" sub="Passes shown on the public registration page, plus discount codes." />
      <div className="grid gap-6 lg:grid-cols-3">
        <div className="space-y-3 lg:col-span-2">
          {tickets.map((t) => (
            <Card key={t.id} className={`flex items-center justify-between gap-4 p-4 ${!t.active ? "opacity-50" : ""}`}>
              <div>
                <div className="flex items-center gap-2">
                  <span className="font-medium text-zinc-100">{t.name}</span>
                  <Badge className="bg-zinc-800 text-zinc-400">{t.audience}</Badge>
                  {!t.active && <Badge className="bg-red-500/10 text-red-600">disabled</Badge>}
                </div>
                <div className="mt-0.5 text-xs text-zinc-500">
                  {formatMoney(t.price)} · {t._count.registrations} sold{t.quantity != null ? ` of ${t.quantity}` : " (unlimited)"}
                  {t.saleEndsAt ? ` · sales end ${fmtDate(t.saleEndsAt)}` : ""}
                </div>
                {t.quantity != null && (
                  <div className="mt-2 h-1.5 w-48 overflow-hidden rounded-full bg-zinc-800">
                    <div className="h-full rounded-full bg-indigo-500" style={{ width: `${Math.min(100, (t._count.registrations / t.quantity) * 100)}%` }} />
                  </div>
                )}
              </div>
              <form action={toggleTicketType.bind(null, id, t.id)}>
                <button className={btn.smSecondary}>{t.active ? "Disable" : "Enable"}</button>
              </form>
            </Card>
          ))}

          <Card className="p-5">
            <h2 className="text-sm font-semibold text-zinc-200">Coupons</h2>
            <div className="mt-3 space-y-2">
              {coupons.length === 0 && <p className="text-sm text-zinc-500">No coupons yet.</p>}
              {coupons.map((c) => (
                <div key={c.id} className={`flex items-center justify-between rounded-lg border border-zinc-800 px-3 py-2 text-sm ${!c.active ? "opacity-50" : ""}`}>
                  <div>
                    <span className="font-mono font-semibold text-zinc-200">{c.code}</span>
                    <span className="ml-3 text-xs text-zinc-500">
                      {c.discountType === "PERCENT" ? `${c.value}% off` : `${formatMoney(c.value)} off`} · used {c.usedCount}{c.maxUses != null ? `/${c.maxUses}` : ""}
                    </span>
                  </div>
                  <form action={toggleCoupon.bind(null, id, c.id)}>
                    <button className={btn.smSecondary}>{c.active ? "Disable" : "Enable"}</button>
                  </form>
                </div>
              ))}
            </div>
            <form action={createCoupon.bind(null, id)} className="mt-4 grid grid-cols-4 gap-2">
              <input name="code" placeholder="CODE" className={`${input} uppercase`} required />
              <select name="discountType" className={input} defaultValue="PERCENT">
                <option value="PERCENT">% off</option>
                <option value="FLAT">₹ off (flat, paise)</option>
              </select>
              <input name="value" type="number" placeholder="Value" required className={input} />
              <div className="flex gap-2">
                <input name="maxUses" type="number" placeholder="Max" className={input} />
                <button className={btn.smSecondary}>Add</button>
              </div>
            </form>
          </Card>
        </div>

        <Card className="h-fit p-5">
          <h2 className="text-sm font-semibold text-zinc-200">New ticket type</h2>
          <form action={createTicketType.bind(null, id)} className="mt-4 space-y-3">
            <Field name="name" title="Name *"><input id="name" name="name" required className={input} placeholder="Early Bird" /></Field>
            <div className="grid grid-cols-2 gap-3">
              <Field name="price" title="Price (₹, 0 = free)"><input id="price" name="price" type="number" min={0} step="0.01" defaultValue={0} className={input} /></Field>
              <Field name="quantity" title="Quantity (blank = ∞)"><input id="quantity" name="quantity" type="number" min={1} className={input} /></Field>
            </div>
            <Field name="audience" title="Audience">
              <select id="audience" name="audience" className={input} defaultValue="ATTENDEE">
                {["ATTENDEE", "STUDENT", "VIP", "SPEAKER", "SPONSOR", "COMPLIMENTARY"].map((a) => <option key={a} value={a}>{a[0] + a.slice(1).toLowerCase()}</option>)}
              </select>
            </Field>
            <Field name="saleEndsAt" title="Sales end"><input id="saleEndsAt" name="saleEndsAt" type="datetime-local" className={input} /></Field>
            <Field name="description" title="Description"><textarea id="description" name="description" rows={2} className={input} /></Field>
            <button className={`${btn.primary} w-full`}>Create ticket type</button>
          </form>
        </Card>
      </div>
    </main>
  );
}
