import { deleteProductAction } from "@/app/admin/actions";
import { Button } from "@/components/ui/button";
import { getAdminProductsData } from "@/lib/admin-data";

export default async function AdminProductsPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; brand?: string }>;
}) {
  const params = await searchParams;
  const { scooters, brands, inventory } = await getAdminProductsData();
  const query = params.q?.toLowerCase() ?? "";
  const brandFilter = params.brand ?? "all";
  const filtered = scooters.filter((scooter: any) => {
    const brandId = scooter.brandId ?? scooter.brand?.id;
    return (
      (!query || scooter.name.toLowerCase().includes(query)) &&
      (brandFilter === "all" || brandId === brandFilter)
    );
  });

  return (
    <div className="space-y-5">
      <div className="flex flex-col justify-between gap-4 md:flex-row md:items-center">
        <div>
          <h1 className="text-2xl font-bold text-navy-deep">Products</h1>
          <p className="text-sm text-navy-muted">Manage scooters, stock, publishing and 3D assets.</p>
        </div>
        <Button href="/admin/products/new" variant="green">Add Product</Button>
      </div>
      <form className="soft-card grid gap-3 p-4 md:grid-cols-[1fr_240px_auto]">
        <input name="q" placeholder="Search products" defaultValue={params.q ?? ""} className="h-11 rounded-xl border border-border px-4 text-sm" />
        <select name="brand" defaultValue={brandFilter} className="h-11 rounded-xl border border-border px-4 text-sm">
          <option value="all">All brands</option>
          {brands.map((brand: any) => (
            <option value={brand.id} key={brand.id}>{brand.name}</option>
          ))}
        </select>
        <Button type="submit">Filter</Button>
      </form>
      <div className="soft-card overflow-x-auto">
        <table className="w-full min-w-[980px] text-left text-sm">
          <thead className="bg-primary-soft text-navy-deep">
            <tr>
              {["Image", "Name", "Brand", "Price", "Stock", "GLB", "USDZ", "Published", "Actions"].map((head) => (
                <th className="px-4 py-3 font-bold" key={head}>{head}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {filtered.map((scooter: any) => {
              const brand = scooter.brand ?? brands.find((item: any) => item.id === scooter.brandId);
              const stock = inventory
                .filter((item: any) => item.scooterId === scooter.id)
                .reduce((sum: number, item: any) => sum + (item.quantity ?? 0), 0);
              const asset = scooter.asset3d;
              return (
                <tr className="border-t border-border" key={scooter.id}>
                  <td className="px-4 py-3"><img src={scooter.thumbnailImage} alt={scooter.name} className="h-14 w-20 rounded-xl object-cover" /></td>
                  <td className="px-4 py-3 font-bold text-navy-deep">{scooter.name}</td>
                  <td className="px-4 py-3">{brand?.name}</td>
                  <td className="px-4 py-3">Rs. {scooter.offerPrice?.toLocaleString?.("en-NP") ?? scooter.offerPrice}</td>
                  <td className="px-4 py-3">{stock}</td>
                  <td className="px-4 py-3">{asset?.glbUrl || scooter.model3dGlbUrl ? "Yes" : "No"}</td>
                  <td className="px-4 py-3">{asset?.usdzUrl || scooter.model3dUsdzUrl ? "Yes" : "No"}</td>
                  <td className="px-4 py-3">{scooter.published ?? true ? "Published" : "Draft"}</td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <Button href={`/admin/products/${scooter.id}/edit`} size="sm" variant="outline">Edit</Button>
                      <Button href="/admin/3d-assets" size="sm" variant="secondary">Manage 3D</Button>
                      <form action={deleteProductAction}>
                        <input type="hidden" name="id" value={scooter.id} />
                        <Button className="bg-red-600 text-white hover:bg-red-700" size="sm" type="submit">Delete</Button>
                      </form>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}
