import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { redirect } from "next/navigation";
import Link from "next/link";
import { formatCurrency, formatDate } from "@/lib/utils";
import { AddProductButton, ToggleProductButton } from "./product-form";
import { ConfirmDeleteButton } from "@/components/ui/confirm-delete-button";
import { deleteProduct } from "./actions";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "Item Catalogue" };

export default async function AdminProductsPage() {
  const session = await auth();
  if (!session?.user) redirect("/login");
  if (!hasPermission(session.user.role, "manage_products")) redirect("/dashboard");

  const products = await db.product.findMany({
    orderBy: { name: "asc" },
    include: {
      lastVendor: true,
      _count: { select: { vendorPrices: true } },
    },
  });

  const canManage = hasPermission(session.user.role, "manage_products") && session.user.role === "ADMIN";

  return (
    <div>
      <div className="mb-6 flex items-center justify-between">
        <h1 className="text-2xl font-semibold text-neutral-900">Item Catalogue</h1>
        {canManage && <AddProductButton />}
      </div>

      <div className="rounded-lg border border-neutral-200 bg-white overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-neutral-50 border-b border-neutral-200">
            <tr>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Name</th>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Code</th>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Description</th>
              <th className="px-4 py-3 text-right font-medium text-neutral-600">Vendors</th>
              <th className="px-4 py-3 text-right font-medium text-neutral-600">Last Price</th>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Last Vendor</th>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Updated</th>
              <th className="px-4 py-3 text-left font-medium text-neutral-600">Status</th>
              {canManage && <th className="px-4 py-3"></th>}
            </tr>
          </thead>
          <tbody className="divide-y divide-neutral-100">
            {products.length === 0 && (
              <tr>
                <td colSpan={canManage ? 9 : 8} className="px-4 py-8 text-center text-neutral-400">
                  No items yet. Items are added automatically when a PO is marked as paid.
                </td>
              </tr>
            )}
            {products.map((product) => (
              <tr key={product.id} className="hover:bg-neutral-50">
                <td className="px-4 py-3">
                  <Link
                    href={`/admin/products/${product.id}`}
                    className="font-medium text-primary-600 hover:underline"
                  >
                    {product.name}
                  </Link>
                </td>
                <td className="px-4 py-3 font-mono text-xs text-neutral-500">{product.code}</td>
                <td className="px-4 py-3 text-neutral-500 max-w-xs truncate">
                  {product.description ?? <span className="italic text-neutral-400">—</span>}
                </td>
                <td className="px-4 py-3 text-right text-neutral-600">
                  {product._count.vendorPrices > 0
                    ? product._count.vendorPrices
                    : <span className="text-neutral-400">—</span>}
                </td>
                <td className="px-4 py-3 text-right text-neutral-700">
                  {product.lastPrice !== null
                    ? formatCurrency(Number(product.lastPrice))
                    : <span className="text-neutral-400 italic">—</span>}
                </td>
                <td className="px-4 py-3 text-neutral-600">
                  {product.lastVendor?.name ?? <span className="italic text-neutral-400">—</span>}
                </td>
                <td className="px-4 py-3 text-neutral-500">{formatDate(product.updatedAt)}</td>
                <td className="px-4 py-3">
                  <span className={`rounded-full px-2.5 py-0.5 text-xs font-medium ${
                    product.isActive ? "bg-success-100 text-success-700" : "bg-neutral-100 text-neutral-500"
                  }`}>
                    {product.isActive ? "Active" : "Inactive"}
                  </span>
                </td>
                {canManage && (
                  <td className="px-4 py-3">
                    <span className="flex items-center gap-3">
                      <ToggleProductButton product={{
                        id: product.id,
                        code: product.code,
                        name: product.name,
                        description: product.description,
                        isActive: product.isActive,
                      }} />
                      <ConfirmDeleteButton onDelete={deleteProduct.bind(null, product.id)} label={product.name} />
                    </span>
                  </td>
                )}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <p className="mt-3 text-xs text-neutral-400">
        Items and vendor prices are updated automatically when a PO is marked as paid.
      </p>
    </div>
  );
}
