import { prisma } from "@/lib/prisma";
import { createFestivalOffer, toggleFestivalOffer, deleteFestivalOffer } from "@/lib/actions/discounts";
import DiscountsTabs from "@/components/admin/DiscountsTabs";
import { formatDate } from "@/lib/format";

export default async function AdminFestivalOffersPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const { error } = await searchParams;
  const offers = await prisma.festivalOffer.findMany({ orderBy: { startsAt: "desc" } });
  const now = new Date();

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Festival Offers</h1>
      <p className="mt-1 text-sm text-stone-500">
        A sitewide % off the whole order during a date range — e.g. a Diwali or Pongal sale. Only applies automatically while the date range is current, and never stacks with a coupon (whichever gives the bigger discount wins).
      </p>

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

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

      <form action={createFestivalOffer} className="grid max-w-2xl grid-cols-2 gap-3 rounded-lg border border-rose-100 bg-white p-4 sm:grid-cols-4">
        <input name="name" required placeholder="Offer name (e.g. Diwali Sale)" className="rounded-md border border-stone-300 px-2 py-2 text-sm sm:col-span-2" />
        <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" />
        <div />
        <label className="text-xs text-stone-500 sm:col-span-2">
          Starts
          <input name="startsAt" type="date" required className="mt-1 block w-full rounded-md border border-stone-300 px-2 py-2 text-sm" />
        </label>
        <label className="text-xs text-stone-500 sm:col-span-2">
          Ends
          <input name="endsAt" type="date" required className="mt-1 block w-full rounded-md border border-stone-300 px-2 py-2 text-sm" />
        </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-4">
          Add offer
        </button>
      </form>

      <div className="mt-8 overflow-hidden rounded-lg border border-rose-100 bg-white">
        {offers.length === 0 ? (
          <p className="p-4 text-sm text-stone-500">No festival offers 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">Discount</th>
                <th className="p-3">Dates</th>
                <th className="p-3">Status</th>
                <th className="p-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {offers.map((o) => {
                const isLive = o.active && o.startsAt <= now && o.endsAt >= now;
                return (
                  <tr key={o.id}>
                    <td className="p-3 font-medium text-stone-800">{o.name}</td>
                    <td className="p-3 text-stone-600">{o.discountPercent}% off</td>
                    <td className="p-3 text-stone-500">
                      {formatDate(o.startsAt)} – {formatDate(o.endsAt)}
                    </td>
                    <td className="p-3">
                      {isLive ? (
                        <span className="rounded-full bg-emerald-100 px-2 py-0.5 text-xs font-medium text-emerald-800">Live now</span>
                      ) : (
                        <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${o.active ? "bg-sky-100 text-sky-800" : "bg-stone-200 text-stone-600"}`}>
                          {o.active ? "Scheduled" : "Inactive"}
                        </span>
                      )}
                    </td>
                    <td className="p-3 text-right">
                      <div className="flex items-center justify-end gap-3">
                        <form action={toggleFestivalOffer.bind(null, o.id)}>
                          <button type="submit" className="text-xs text-stone-500 hover:text-rose-700">
                            {o.active ? "Deactivate" : "Activate"}
                          </button>
                        </form>
                        <form action={deleteFestivalOffer.bind(null, o.id)}>
                          <button type="submit" className="text-xs text-stone-400 hover:text-red-700">
                            Delete
                          </button>
                        </form>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
