import { Metadata } from "next";
import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { serialize } from "@/lib/serialize";
import { formatPrice } from "@/lib/utils";
import { Plus, Edit, Package } from "lucide-react";
import AdminProductActions from "./AdminProductActions";

export const metadata: Metadata = { title: "Manage Products" };

export default async function AdminProductsPage({ searchParams }: { searchParams: Promise<{ page?: string; q?: string }> }) {
  const session = await getServerSession(authOptions);
  if (!session || !["ADMIN","SUPER_ADMIN"].includes(session.user?.role || "")) redirect("/");

  const params = await searchParams;
  const page = parseInt(params.page || "1");
  const limit = 15;
  const search = params.q;
  const where = search ? { OR: [{ name: { contains: search, mode: "insensitive" as const } }, { brand: { name: { contains: search, mode: "insensitive" as const } } }] } : {};

  const [rawProducts, total] = await Promise.all([
    prisma.product.findMany({ where, include: { brand: true, category: true }, orderBy: { createdAt: "desc" }, skip: (page-1)*limit, take: limit }),
    prisma.product.count({ where }),
  ]);
  const products = serialize(rawProducts) as unknown as Array<{ id: string; name: string; price: number; stock: number; status: string; featured: boolean; images: string[]; brand: { name: string }; category: { name: string } }>;
  const pages = Math.ceil(total / limit);

  return (
    <div className="max-w-7xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-black text-slate-900">Products</h1>
          <p className="text-slate-500 text-sm">{total} products total</p>
        </div>
        <Link href="/admin/products/new" className="flex items-center gap-2 bg-sky-500 text-white px-4 py-2.5 rounded-xl font-bold text-sm hover:bg-sky-600 transition-colors">
          <Plus className="w-4 h-4" /> Add Product
        </Link>
      </div>

      {/* Search */}
      <form className="mb-5">
        <input name="q" defaultValue={search} placeholder="Search products..." className="w-full sm:w-80 px-4 py-2.5 rounded-xl border-2 border-slate-200 focus:border-sky-400 focus:outline-none text-sm" />
      </form>

      <div className="bg-white rounded-2xl border border-slate-100 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-slate-50 border-b border-slate-100">
              <tr>
                {["Product","Brand","Category","Price","Stock","Status","Actions"].map((h) => (
                  <th key={h} className="px-4 py-3 text-left text-xs font-bold text-slate-500 uppercase tracking-wider whitespace-nowrap">{h}</th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-50">
              {products.map((product) => (
                <tr key={product.id} className="hover:bg-slate-50 transition-colors">
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-3">
                      <div className="relative w-12 h-10 rounded-lg overflow-hidden bg-slate-100 shrink-0">
                        {product.images[0] ? (
                          <Image src={product.images[0]} alt={product.name} fill className="object-cover" />
                        ) : <Package className="w-5 h-5 text-slate-300 absolute inset-0 m-auto" />}
                      </div>
                      <p className="text-sm font-semibold text-slate-800 max-w-44 line-clamp-2">{product.name}</p>
                    </div>
                  </td>
                  <td className="px-4 py-3 text-sm text-slate-600 whitespace-nowrap">{product.brand.name}</td>
                  <td className="px-4 py-3 text-sm text-slate-600 whitespace-nowrap">{product.category.name}</td>
                  <td className="px-4 py-3 text-sm font-bold text-slate-800 whitespace-nowrap">{formatPrice(product.price)}</td>
                  <td className="px-4 py-3">
                    <span className={`text-sm font-bold ${product.stock === 0 ? "text-red-500" : product.stock <= 5 ? "text-amber-500" : "text-emerald-600"}`}>
                      {product.stock}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`text-xs font-bold px-2 py-1 rounded-full ${product.status === "ACTIVE" ? "bg-emerald-100 text-emerald-700" : "bg-slate-100 text-slate-500"}`}>
                      {product.status}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <Link href={`/admin/products/${product.id}`} className="p-2 rounded-lg hover:bg-sky-50 text-sky-600 transition-colors">
                        <Edit className="w-4 h-4" />
                      </Link>
                      <AdminProductActions productId={product.id} />
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {products.length === 0 && (
          <div className="text-center py-16">
            <Package className="w-12 h-12 text-slate-200 mx-auto mb-3" />
            <p className="text-slate-500 font-medium">No products found</p>
          </div>
        )}

        {pages > 1 && (
          <div className="flex justify-center gap-2 px-4 py-4 border-t border-slate-100">
            {Array.from({ length: pages }, (_, i) => i + 1).map((p) => (
              <a key={p} href={`?page=${p}${search ? `&q=${search}` : ""}`}
                className={`w-9 h-9 rounded-lg flex items-center justify-center text-sm font-bold ${p === page ? "bg-sky-500 text-white" : "border border-slate-200 text-slate-600 hover:border-sky-300"}`}>{p}</a>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
