import { db } from "@/lib/db";
import { requireConfAccess } from "@/lib/rbac";
import { Avatar, Card, EmptyState, PageHeader, btn, input, Field, Badge } from "@/components/ui";
import { formatMoney } from "@/lib/utils";
import { SPONSOR_TIERS, SPONSOR_TIER_LABELS } from "@/lib/constants";
import { createSponsor, deleteSponsor } from "../actions";

export const metadata = { title: "Sponsors" };

export default async function SponsorsAdminPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ error?: string }>;
}) {
  const { id } = await params;
  const { error } = await searchParams;
  await requireConfAccess(id, "sponsors.manage");
  const sponsors = await db.sponsor.findMany({ where: { conferenceId: id }, orderBy: { amount: "desc" } });
  const total = sponsors.reduce((s, x) => s + x.amount, 0);

  return (
    <main>
      <PageHeader title="Sponsors & exhibitors" sub={`${sponsors.length} sponsors · ${formatMoney(total)} committed`} />
      {error && <div className="mb-4 rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-600">{error}</div>}
      <div className="grid gap-6 lg:grid-cols-3">
        <div className="space-y-3 lg:col-span-2">
          {sponsors.length === 0 && <EmptyState title="No sponsors yet" body="Add sponsors here — they appear automatically on the public site, grouped by tier." />}
          {sponsors.map((s) => (
            <Card key={s.id} className="flex items-center justify-between gap-4 p-4">
              <div className="flex min-w-0 items-center gap-3">
                {s.logoUrl ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img src={s.logoUrl} alt={s.name} className="h-12 w-12 shrink-0 rounded-xl border border-white/70 bg-white object-contain p-1" />
                ) : (
                  <Avatar name={s.name} size={12} />
                )}
                <div>
                <div className="flex items-center gap-2">
                  <span className="font-medium text-zinc-100">{s.name}</span>
                  <Badge className="bg-amber-500/10 text-amber-600">{SPONSOR_TIER_LABELS[s.tier] ?? s.tier}</Badge>
                  {s.boothNumber && <span className="text-xs text-zinc-500">Booth {s.boothNumber}</span>}
                </div>
                <div className="mt-0.5 text-xs text-zinc-500">
                  {formatMoney(s.amount)}{s.website ? ` · ${s.website}` : ""}
                </div>
                </div>
              </div>
              <form action={deleteSponsor.bind(null, id, s.id)}>
                <button className="rounded-md px-2 py-1 text-xs text-zinc-600 transition hover:bg-red-500/10 hover:text-red-600">✕</button>
              </form>
            </Card>
          ))}
        </div>
        <Card className="h-fit p-5">
          <h2 className="text-sm font-semibold text-zinc-200">Add sponsor</h2>
          <form action={createSponsor.bind(null, id)} className="mt-4 space-y-3">
            <Field name="name" title="Name *"><input id="name" name="name" required className={input} /></Field>
            <div className="grid grid-cols-2 gap-3">
              <Field name="tier" title="Tier">
                <select id="tier" name="tier" className={input} defaultValue="GOLD">
                  {SPONSOR_TIERS.map((t) => <option key={t} value={t}>{SPONSOR_TIER_LABELS[t]}</option>)}
                </select>
              </Field>
              <Field name="amount" title="Amount (₹)"><input id="amount" name="amount" type="number" min={0} className={input} /></Field>
            </div>
            <Field name="logo" title="Logo (≤5 MB)">
              <input id="logo" name="logo" type="file" accept="image/*" className="w-full cursor-pointer rounded-xl border border-white/80 bg-white/70 px-3 py-2 text-sm text-zinc-400 shadow-sm backdrop-blur file:mr-3 file:cursor-pointer file:rounded-lg file:border-0 file:bg-indigo-500/10 file:px-3 file:py-1 file:text-xs file:font-semibold file:text-indigo-600" />
            </Field>
            <Field name="website" title="Website"><input id="website" name="website" className={input} placeholder="https://…" /></Field>
            <Field name="boothNumber" title="Booth number"><input id="boothNumber" name="boothNumber" className={input} placeholder="A-12" /></Field>
            <Field name="description" title="Description"><textarea id="description" name="description" rows={2} className={input} /></Field>
            <button className={`${btn.primary} w-full`}>Add sponsor</button>
          </form>
        </Card>
      </div>
    </main>
  );
}
