import Link from 'next/link';
import { prisma } from '@/lib/prisma';
import AdminNav from '@/components/AdminNav';
import { deletePromotion } from './actions';

function statusFor(promotion: { startsAt: Date | null; endsAt: Date | null }, now: Date) {
  if (promotion.startsAt && promotion.startsAt > now) return { label: 'Scheduled', className: 'bg-splash-orange/10 text-splash-orange' };
  if (promotion.endsAt && promotion.endsAt < now) return { label: 'Ended', className: 'bg-muted/10 text-muted' };
  return { label: 'Active now', className: 'bg-splash-blue/10 text-splash-blue' };
}

function formatDate(d: Date | null) {
  if (!d) return null;
  return d.toLocaleDateString(undefined, { dateStyle: 'medium' });
}

export default async function PromotionsPage() {
  const promotions = await prisma.promotion.findMany({
    orderBy: { createdAt: 'desc' },
    include: { products: { select: { id: true } } },
  });
  const now = new Date();

  return (
    <div className="mx-auto max-w-2xl px-6 py-12">
      <AdminNav />
      <div className="flex items-baseline justify-between">
        <h1 className="font-display text-3xl">Promotions</h1>
        <Link
          href="/admin/promotions/new"
          className="border border-ink px-4 py-2 text-sm hover:border-clay hover:bg-clay hover:text-paper"
        >
          + Add promotion
        </Link>
      </div>
      <p className="mt-2 text-sm text-muted">
        A banner shown at the top of every page while its date window is active. If more than one
        is active at once, the most recently created one shows.
      </p>

      {promotions.length === 0 ? (
        <p className="mt-8 text-sm text-muted">No promotions yet.</p>
      ) : (
        <div className="mt-8 divide-y divide-line border-t border-line">
          {promotions.map((p) => {
            const status = statusFor(p, now);
            return (
              <div key={p.id} className="flex items-center gap-4 py-4">
                <div className="flex-1">
                  <p className="font-medium">{p.message}</p>
                  <p className="tag-label mt-0.5">
                    {p.discountPercent}% off — {p.scope === 'ALL' ? 'All items' : `${p.products.length} item${p.products.length === 1 ? '' : 's'}`}
                    {' · '}
                    {formatDate(p.startsAt) ?? 'Starts immediately'} — {formatDate(p.endsAt) ?? 'no end date'}
                  </p>
                </div>
                <span className={`tag-label rounded-full px-3 py-1 ${status.className}`}>{status.label}</span>
                <Link href={`/admin/promotions/${p.id}/edit`} className="tag-label hover:text-clay">
                  Edit
                </Link>
                <form action={deletePromotion}>
                  <input type="hidden" name="id" value={p.id} />
                  <button type="submit" className="tag-label text-muted hover:text-splash-pink">
                    Delete
                  </button>
                </form>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
