import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { transferStock } from "@/lib/actions/inventory";
import InventoryTabs from "@/components/admin/InventoryTabs";
import { formatDate } from "@/lib/format";

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

  const [products, warehouses, movements] = await Promise.all([
    prisma.product.findMany({ select: { id: true, name: true }, orderBy: { name: "asc" } }),
    prisma.warehouse.findMany({ orderBy: { name: "asc" } }),
    prisma.stockMovement.findMany({
      where: { type: "transfer" },
      include: { product: { select: { name: true } }, fromWarehouse: true, toWarehouse: true },
      orderBy: { createdAt: "desc" },
      take: 50,
    }),
  ]);

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Stock Transfer</h1>
      <p className="mt-1 text-sm text-stone-500">
        Log stock moved between warehouses/godowns. This is a movement record — it doesn&apos;t change a product&apos;s total stock count on the Stock page.
      </p>

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

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

      {warehouses.length < 2 ? (
        <div className="max-w-2xl rounded-lg border border-dashed border-rose-200 bg-rose-50/40 p-4 text-sm text-stone-600">
          You need at least two warehouses to log a transfer.{" "}
          <Link href="/iv-manage-84x2/inventory/warehouses" className="font-medium text-rose-700 hover:underline">
            Add warehouses →
          </Link>
        </div>
      ) : (
        <form action={transferStock} className="grid max-w-2xl grid-cols-1 gap-3 rounded-lg border border-rose-100 bg-white p-4 sm:grid-cols-2">
          <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}
              </option>
            ))}
          </select>
          <select name="fromWarehouseId" required className="rounded-md border border-stone-300 px-2 py-2 text-sm">
            <option value="">From warehouse…</option>
            {warehouses.map((w) => (
              <option key={w.id} value={w.id}>
                {w.name}
              </option>
            ))}
          </select>
          <select name="toWarehouseId" required className="rounded-md border border-stone-300 px-2 py-2 text-sm">
            <option value="">To warehouse…</option>
            {warehouses.map((w) => (
              <option key={w.id} value={w.id}>
                {w.name}
              </option>
            ))}
          </select>
          <input name="quantity" type="number" min={1} required placeholder="Quantity" className="rounded-md border border-stone-300 px-2 py-2 text-sm" />
          <input name="reason" placeholder="Notes (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-2"
          >
            Log transfer
          </button>
        </form>
      )}

      <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">Qty</th>
              <th className="p-3">From</th>
              <th className="p-3">To</th>
              <th className="p-3">Notes</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-rose-100">
            {movements.length === 0 ? (
              <tr>
                <td colSpan={6} className="p-4 text-sm text-stone-500">
                  No transfers 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 text-stone-700">{m.quantity}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{m.fromWarehouse?.name ?? "—"}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{m.toWarehouse?.name ?? "—"}</td>
                  <td className="p-3 text-stone-500">{m.reason ?? "—"}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}
