import { notFound } from "next/navigation";
import { prisma } from "@/lib/db";
import { parseSpecFields, parseSpecs } from "@/lib/serialize";
import { ProductForm } from "@/components/admin/ProductForm";
import { deleteProduct } from "@/app/admin/actions";

export const dynamic = "force-dynamic";

export default async function EditProductPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const [product, categories] = await Promise.all([
    prisma.product.findUnique({
      where: { id },
      include: { images: { orderBy: { sortOrder: "asc" } } },
    }),
    prisma.category.findMany({ orderBy: { sortOrder: "asc" } }),
  ]);
  if (!product) notFound();

  const options = categories.map((c) => ({
    id: c.id,
    name: c.name,
    specFields: parseSpecFields(c.specFields),
  }));

  const initial = {
    id: product.id,
    title: product.title,
    description: product.description,
    brand: product.brand,
    price: product.price,
    mrp: product.mrp,
    condition: product.condition,
    warrantyMonths: product.warrantyMonths,
    quantity: product.quantity,
    featured: product.featured,
    status: product.status,
    categoryId: product.categoryId,
    specs: parseSpecs(product.specs),
    images: product.images.map((i) => ({ id: i.id, url: i.url })),
  };

  return (
    <div className="space-y-4">
      <div className="flex items-start justify-between gap-3">
        <div>
          <a href="/admin/products" className="text-sm text-slate-400 hover:text-brand-600">
            ← Back to products
          </a>
          <h2 className="mt-1 text-lg font-bold text-slate-900">Edit product</h2>
        </div>
        <a
          href={`/product/${product.slug}`}
          target="_blank"
          className="rounded-lg border border-slate-300 px-3 py-2 text-sm font-medium text-slate-700 hover:bg-slate-100"
        >
          View on store ↗
        </a>
      </div>

      <ProductForm categories={options} initial={initial} />

      <form
        action={deleteProduct}
        className="mt-8 rounded-xl border border-rose-200 bg-rose-50 p-4"
      >
        <input type="hidden" name="id" value={product.id} />
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <p className="text-sm font-semibold text-rose-800">Delete this product</p>
            <p className="text-xs text-rose-600">
              This permanently removes the listing. Past orders keep their record.
            </p>
          </div>
          <button className="rounded-lg bg-rose-600 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-700">
            Delete product
          </button>
        </div>
      </form>
    </div>
  );
}
