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

export default async function CategoriesPage({ searchParams }: { searchParams: { error?: string } }) {
  const categories = await prisma.category.findMany({ orderBy: { createdAt: 'asc' } });
  const counts = await prisma.product.groupBy({ by: ['category'], _count: true });
  const countFor = (slug: string) => counts.find((c) => c.category === slug)?._count ?? 0;

  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">Categories</h1>
        <Link
          href="/admin/categories/new"
          className="border border-ink px-4 py-2 text-sm hover:border-clay hover:bg-clay hover:text-paper"
        >
          + Add category
        </Link>
      </div>

      {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 category — there are still products using it. Move or delete those
          products first.
        </div>
      )}

      <div className="mt-8 divide-y divide-line border-t border-line">
        {categories.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.slug)} product{countFor(c.slug) === 1 ? '' : 's'}
              </p>
            </div>

            <form action={updateCategoryVisibility} className="flex items-center gap-3">
              <input type="hidden" name="id" value={c.id} />
              <label className="flex items-center gap-1.5 text-xs text-muted">
                <input
                  type="checkbox"
                  name="showOnPersonalised"
                  value="1"
                  defaultChecked={c.showOnPersonalised}
                  className="h-3.5 w-3.5 accent-clay"
                />
                Personalised
              </label>
              <label className="flex items-center gap-1.5 text-xs text-muted">
                <input
                  type="checkbox"
                  name="showOnProducts"
                  value="1"
                  defaultChecked={c.showOnProducts}
                  className="h-3.5 w-3.5 accent-clay"
                />
                Products
              </label>
              <button type="submit" className="tag-label hover:text-clay">
                Save
              </button>
            </form>

            <form action={deleteCategory}>
              <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>
  );
}
