/* eslint-disable @typescript-eslint/no-explicit-any */
import { Suspense } from "react";
import Navbar from "@/components/shared/Navbar";
import Footer from "@/components/shared/Footer";
import ProductsClient from "./ProductsClient"; // reload HMR
import ProductsSkeleton from "@/components/skeletons/ProductsSkeleton";
import { getCategories, getProducts, getBrands, getFeaturedProducts } from "@/services/products/product.service";
import type { Metadata } from "next";

export const revalidate = 60;

export const metadata: Metadata = {
  title: "All Products | Electronics Retailer",
  description: "Browse our full range of genuine electronics, home appliances and accessories.",
};

interface PageProps {
  searchParams: Promise<{
    page?: string;
    search?: string;
    category?: string;
    brand?: string;
    min_price?: string;
    max_price?: string;
    sort?: string;
    featured?: string;
    specifications?: string;
  }>;
}

export default async function Page({ searchParams }: PageProps) {
  const params = await searchParams;
  const { page, search, category, brand, min_price, max_price, sort, featured, specifications } = params;

  return (
    <>
      <Navbar />
      <main id="main-content" className="min-h-screen bg-white pt-24 text-slate-900">
        <Suspense fallback={<div className="container mx-auto px-6 py-10"><ProductsSkeleton /></div>}>
          <ProductsLoader
            page={page}
            search={search}
            category={category}
            brand={brand}
            minPrice={min_price}
            maxPrice={max_price}
            sort={sort}
            featured={featured}
            specifications={specifications}
          />
        </Suspense>
      </main>
      <Footer />
    </>
  );
}

async function ProductsLoader({
  page,
  search,
  category,
  brand,
  minPrice,
  maxPrice,
  sort,
  featured,
  specifications,
}: {
  page?: string;
  search?: string;
  category?: string;
  brand?: string;
  minPrice?: string;
  maxPrice?: string;
  sort?: string;
  featured?: string;
  specifications?: string;
}) {
  const currentPage = Number(page) || 1;
  const isFeatured = featured === "true";

  const parsePrice = (v?: string) => {
    if (!v) return undefined;
    const n = Number(v);
    return Number.isFinite(n) && n >= 0 ? n : undefined;
  };

  let productsData: any = null;
  let categoriesData: any[] = [];
  let brandsData: any[] = [];

  try {
    const promises = [
      getCategories().catch(() => []),
      getBrands().catch(() => []),
    ];

    if (isFeatured) {
      promises.push(
        getFeaturedProducts(currentPage, 9).catch((err) => {
          console.error("Failed to fetch featured products:", err);
          return null;
        })
      );
    } else {
      promises.push(
        getProducts({
          page: currentPage,
          limit: 9,
          search,
          category,
          brand,
          min_price: parsePrice(minPrice),
          max_price: parsePrice(maxPrice),
          sort: sort as any,
          specifications,
        }).catch((err) => {
          console.error("Failed to fetch products:", err);
          return null;
        })
      );
    }

    const [categories, brands, products] = await Promise.all(promises);
    categoriesData = categories || [];
    brandsData = brands || [];
    productsData = products || { data: [], total: 0, limit: 9, page: 1 };
  } catch (error) {
    console.error("Error loading products page data:", error);
  }

  const initialProducts = productsData?.data || [];
  const totalProducts = productsData?.total || 0;
  const totalPages = Math.ceil(totalProducts / (productsData?.limit || 9));

  return (
    <ProductsClient
      initialProducts={initialProducts}
      categories={categoriesData}
      brands={brandsData}
      totalProducts={totalProducts}
      totalPages={totalPages}
      currentPage={currentPage}
      filterParams={{ search, category, brand, minPrice, maxPrice, sort, featured, specifications }}
    />
  );
}
