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

export default async function CollectionsPage({ searchParams }: { searchParams: { error?: string } }) {
  const collections = await prisma.collection.findMany({ orderBy: { createdAt: 'asc' } });
  const occasions = collections.filter((c) => c.group === 'OCCASION');
  const recipients = collections.filter((c) => c.group === 'RECIPIENT');

  const counts = await Promise.all(
    collections.map((c) => prisma.product.count({ where: { collections: { some: { id: c.id } } } })),
  );
  const countFor = (id: string) => counts[collections.findIndex((c) => c.id === id)] ?? 0;

  const Section = ({ title, items }: { title: string; items: typeof collections }) => (
    <div>
      <h2 className="tag-label mt-10 mb-3 text-ink">{title}</h2>
      {items.length === 0 ? (
        <p className="text-sm text-muted">None yet.</p>
      ) : (
        <div className="divide-y divide-line border-t border-line">
          {items.map((c) => (
            <div key={c.id} className="flex items-center gap-4 py-4">
              <div className="flex-1">
                <p className="font-medium">{c.name}</p>
                <p className="tag-label mt-0.5">
                  {countFor(c.id)} product{countFor(c.id) === 1 ? '' : 's'}
                </p>
              </div>
              <form action={deleteCollection}>
                <input type="hidden" name="id" value={c.id} />
                <button type="submit" className="tag-label text-muted hover:text-splash-pink">
                  Delete
                </button>
              </form>
            </div>
          ))}
        </div>
      )}
    </div>
  );

  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">Collections</h1>
        <Link
          href="/admin/collections/new"
          className="border border-ink px-4 py-2 text-sm hover:border-clay hover:bg-clay hover:text-paper"
        >
          + Add collection
        </Link>
      </div>
      <p className="mt-2 text-sm text-muted">
        These power the &quot;Occasions&quot; and &quot;Gifts For&quot; menus, and are tagged onto
        products from each product&apos;s edit page.
      </p>

      {searchParams.error === 'in_use' && (
        <div className="mt-6 border border-splash-orange bg-splash-orange/5 p-4 text-sm">
          Can&apos;t delete that — there are still products tagged with it. Untag those products
          first.
        </div>
      )}

      <Section title="Occasions" items={occasions} />
      <Section title="Gifts for" items={recipients} />
    </div>
  );
}
