import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { updateStock, updatePurchasePrice, updateWeight, updateStockSellingPrice } from "@/lib/actions/products";
import ScrollableTable from "@/components/admin/ScrollableTable";
import SaveIconButton from "@/components/admin/SaveIconButton";
import InventoryTabs from "@/components/admin/InventoryTabs";

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

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Cost &amp; Weight</h1>
      <p className="mt-1 text-sm text-stone-500">
        Track inventory, cost vs. selling price, and per-product weight (for shipping cost calculation — couriers
        charge by weight). Leave any field blank to keep it &ldquo;not tracked.&rdquo; Products with variants (color/size etc.)
        track stock per variant instead — manage those from the product&apos;s edit page.
      </p>

      <InventoryTabs active="/iv-manage-84x2/stock" />

      {error && <p className="mt-4 rounded-md bg-red-50 px-3 py-2 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      <div className="mt-6">
        <ScrollableTable>
          <table className="w-full min-w-[900px] text-sm">
            <thead className="sticky top-0 z-10 bg-rose-50 text-left text-xs uppercase text-stone-500">
              <tr>
                <th className="p-3">Name</th>
                <th className="p-3">Category</th>
                <th className="p-3">Purchase price</th>
                <th className="p-3">Selling price</th>
                <th className="p-3">Weight (g)</th>
                <th className="p-3">Stock</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {products.map((p) => (
                <tr key={p.id}>
                  <td className="whitespace-nowrap p-3">
                    <Link href={`/iv-manage-84x2/products/${p.id}`} className="font-medium text-rose-700 hover:underline">
                      {p.name}
                    </Link>
                  </td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{p.category.name}</td>
                  <td className="whitespace-nowrap p-3">
                    <form action={updatePurchasePrice.bind(null, p.id)} className="flex items-center gap-1.5">
                      <span className="text-stone-500">₹</span>
                      <input
                        type="number"
                        name="purchasePrice"
                        min={0}
                        step="0.01"
                        placeholder="Cost"
                        defaultValue={p.purchasePrice !== null ? p.purchasePrice / 100 : ""}
                        className="w-20 rounded border border-stone-300 px-2 py-1 text-sm"
                      />
                      <SaveIconButton />
                    </form>
                  </td>
                  <td className="whitespace-nowrap p-3">
                    <form action={updateStockSellingPrice.bind(null, p.id)} className="flex items-center gap-1.5">
                      <span className="text-stone-500">₹</span>
                      <input
                        type="number"
                        name="basePrice"
                        min={0.01}
                        step="0.01"
                        defaultValue={p.basePrice / 100}
                        className="w-20 rounded border border-stone-300 px-2 py-1 text-sm"
                      />
                      <SaveIconButton />
                    </form>
                  </td>
                  <td className="whitespace-nowrap p-3">
                    <form action={updateWeight.bind(null, p.id)} className="flex items-center gap-1.5">
                      <input
                        type="number"
                        name="weightGrams"
                        min={0}
                        placeholder="g"
                        defaultValue={p.weightGrams ?? ""}
                        className="w-20 rounded border border-stone-300 px-2 py-1 text-sm"
                      />
                      <SaveIconButton />
                    </form>
                  </td>
                  <td className="whitespace-nowrap p-3">
                    {p._count.variants > 0 ? (
                      <span className="text-xs text-stone-500">
                        Has {p._count.variants} variant{p._count.variants > 1 ? "s" : ""} —{" "}
                        <Link href={`/iv-manage-84x2/products/${p.id}`} className="text-rose-700 hover:underline">
                          manage per variant
                        </Link>
                      </span>
                    ) : (
                      <form action={updateStock.bind(null, p.id)} className="flex items-center gap-2">
                        <input
                          type="number"
                          name="stock"
                          min={0}
                          placeholder="Unlimited"
                          defaultValue={p.stock ?? ""}
                          className="w-24 rounded border border-stone-300 px-2 py-1 text-sm"
                        />
                        <SaveIconButton />
                        {p.stock !== null && (
                          <span
                            className={`rounded-full px-2 py-0.5 text-xs font-medium ${
                              p.stock > 0 ? "bg-emerald-100 text-emerald-800" : "bg-red-100 text-red-800"
                            }`}
                          >
                            {p.stock > 0 ? "In stock" : "Out of stock"}
                          </span>
                        )}
                      </form>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </ScrollableTable>
      </div>
    </div>
  );
}
