import { prisma } from "@/lib/prisma";
import { adjustStock } from "@/lib/actions/inventory";
import InventoryTabs from "@/components/admin/InventoryTabs";
import { formatDate } from "@/lib/format";

export default async function AdminStockAdjustmentsPage({
  searchParams,
}: {
  searchParams: Promise<{ error?: string }>;
}) {
  const { error } = await searchParams;

  const [products, movements] = await Promise.all([
    prisma.product.findMany({
      where: { variants: { none: {} } },
      select: { id: true, name: true, stock: true },
      orderBy: { name: "asc" },
    }),
    prisma.stockMovement.findMany({
      where: { type: "adjustment" },
      include: { product: { select: { name: true } } },
      orderBy: { createdAt: "desc" },
      take: 50,
    }),
  ]);

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Stock Adjustment</h1>
      <p className="mt-1 text-sm text-stone-500">
        Correct stock counts by hand — e.g. a physical recount found extra or missing units. Every adjustment is logged below.
      </p>

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

      {error && <p className="mb-4 text-sm text-red-700">{decodeURIComponent(error)}</p>}

      <form action={adjustStock} className="grid max-w-2xl grid-cols-1 gap-3 rounded-lg border border-rose-100 bg-white p-4 sm:grid-cols-4">
        <select name="productId" required className="rounded-md border border-stone-300 px-2 py-2 text-sm sm:col-span-2">
          <option value="">Select product…</option>
          {products.map((p) => (
            <option key={p.id} value={p.id}>
              {p.name} (current: {p.stock ?? "unlimited"})
            </option>
          ))}
        </select>
        <input
          name="delta"
          type="number"
          required
          placeholder="+/- qty (e.g. -3 or 5)"
          className="rounded-md border border-stone-300 px-2 py-2 text-sm"
        />
        <input name="reason" placeholder="Reason (optional)" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
        <button
          type="submit"
          className="col-span-1 rounded-md bg-rose-700 px-4 py-2 text-sm font-semibold text-white hover:bg-rose-800 sm:col-span-4"
        >
          Apply adjustment
        </button>
      </form>
      <p className="mt-2 max-w-2xl text-xs text-stone-400">
        Products with variants aren&apos;t listed here — variant stock is set when you add the variant on the product&apos;s edit page.
      </p>

      <div className="mt-8 overflow-hidden rounded-lg border border-rose-100 bg-white">
        <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">Date</th>
              <th className="p-3">Product</th>
              <th className="p-3">Change</th>
              <th className="p-3">Reason</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-rose-100">
            {movements.length === 0 ? (
              <tr>
                <td colSpan={4} className="p-4 text-sm text-stone-500">
                  No adjustments logged yet.
                </td>
              </tr>
            ) : (
              movements.map((m) => (
                <tr key={m.id}>
                  <td className="whitespace-nowrap p-3 text-stone-500">{formatDate(m.createdAt)}</td>
                  <td className="whitespace-nowrap p-3 font-medium text-stone-800">{m.product.name}</td>
                  <td className="whitespace-nowrap p-3">
                    <span className={m.quantity >= 0 ? "text-emerald-700" : "text-red-700"}>
                      {m.quantity >= 0 ? `+${m.quantity}` : m.quantity}
                    </span>
                  </td>
                  <td className="p-3 text-stone-500">{m.reason ?? "—"}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
