import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { createCollection, deleteCollection } from "@/lib/actions/collections";

export default async function AdminCollectionsPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const { error } = await searchParams;
  const collections = await prisma.collection.findMany({
    orderBy: { name: "asc" },
    include: { _count: { select: { products: true } } },
  });

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Collections</h1>
      <p className="mt-1 text-sm text-stone-500">
        Curated groupings shown on the homepage (e.g. &ldquo;Wedding Favorites&rdquo;, &ldquo;Budget Picks&rdquo;) — a product can belong to any category and still be featured in a collection.
      </p>

      <form action={createCollection} className="mt-6 flex max-w-md gap-2">
        <input
          type="text"
          name="name"
          required
          placeholder="New collection name"
          className="flex-1 rounded-md border border-stone-300 px-3 py-2 text-sm"
        />
        <button type="submit" className="rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800">
          Add
        </button>
      </form>
      {error && <p className="mt-2 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      <div className="mt-6 overflow-hidden rounded-lg border border-rose-100 bg-white">
        {collections.length === 0 ? (
          <p className="p-4 text-sm text-stone-500">No collections 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">Products</th>
                <th className="p-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {collections.map((c) => (
                <tr key={c.id}>
                  <td className="p-3">
                    <Link href={`/iv-manage-84x2/collections/${c.id}`} className="font-medium text-rose-700 hover:underline">
                      {c.name}
                    </Link>
                  </td>
                  <td className="p-3 text-stone-500">{c._count.products}</td>
                  <td className="p-3 text-right">
                    <form action={deleteCollection.bind(null, c.id)}>
                      <button type="submit" className="text-xs text-stone-400 hover:text-red-700">
                        Delete
                      </button>
                    </form>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
