"use client"
import React, { useEffect } from "react";
import CardNormal, { ProductCardSkeleton } from "src/components/Cards/CardNormal";
import Paginate from "src/components/Paginate";
import graphql from "src/utils/graphql";
import Filters from "./Filters";
import { useParams, useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
const brandAndCategoriesGQL = `
  query Categories($locale: I18NLocaleCode) {
    categories(locale: $locale,pagination: { start: 0, limit: 50 }) {
        documentId
        slug
        title
    }
    brands(locale: $locale, pagination: { start: 0, limit: 50 }) {
        title
        documentId
        slug
    }
    subcategories(locale: $locale, pagination: { start: 0, limit: 50 }) {
        title
        documentId
        slug
    }
}

`

const productsGQL = `
query Products_connection(
    $locale: I18NLocaleCode
    $page: Int
    $pageSize: Int
    $category: String
    $brand: String
    $subcategory: String
) {
    products_connection(
        pagination: { page: $page, pageSize: $pageSize }
        filters: {
            or: [
                { category: { slug: { eqi: $category } } }
                { brand: { slug: { eqi: $brand } } }
                { brand: { subcategories: { slug: { containsi: $subcategory } } } }
                { subcategories: { slug: { containsi: $subcategory } } }
            ]
        }
        locale: $locale
        sort: ["order:asc"]
    ) {
        nodes {
            documentId
            title
            images {
                documentId
                alternativeText
                url
            }
            category {
                title
                documentId
                slug
            }
            brand {
                documentId
                title
                slug
                image {
                    documentId
                    alternativeText
                    url
                }
                description
            }
            slug
        }
        pageInfo {
            total
            page
            pageSize
            pageCount
        }
    }
}



`




const ProductsListingPage = () => {
  const params = useParams()
  const searchParams = useSearchParams()
  const { category } = params
  const [loading, setLoading] = React.useState(true)
  const [pageInfo, setPageInfo] = React.useState({ page: 1, pageSize: 12, total: 0, pageCount: 0 })
  const [products, setProducts] = React.useState([])
  const [brands, setBrands] = React.useState([])
  const [categories, setCategories] = React.useState([])
  const [subcategories, setSubcategories] = React.useState([])
  const getBrandsAndCategories = async () => {
    const { brands, categories,subcategories } = await graphql(brandAndCategoriesGQL, { locale: "en" });
    setBrands(brands)
    setCategories(categories)
    setSubcategories(subcategories)

  }
  const getProducts = async () => {
    setLoading(true)

    const page = parseInt(searchParams.get("page")) || 1
    const { products_connection: { nodes, pageInfo } } = await graphql(productsGQL, {
      locale: "en",
      page: page,
      pageSize: 12,
      brand: category,
      category: category,
      subcategory: category,
    })
    setProducts(nodes)
    setPageInfo(pageInfo)
    setLoading(false)
  }


  useEffect(() => {
    getBrandsAndCategories()
  }, [])

  useEffect(() => {
    getProducts(category)
  }, [searchParams])

  
  const t = useTranslations("PLP")
  return (
    <>
      {
        brands && brands.length > 0 && categories && categories.length > 0 &&
        <Filters subCategories={subcategories} brands={brands} categories={categories} />
      }
      <div className="flex flex-col w-full items-center justify-center ">
        <div className="px-2 pb-20 w-full">
          <div className="flex">
            <div>
              <h1 className="text-3xl font-bold   ">
                { t("title")}
              </h1>
              <p className="mb-0 text-sm text-gray-400 xs:text-center ">
                {t("subtitle")}
              </p>
            </div>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6 mt-10 w-full">
            {!loading && products.map((product, index) => (
              <div key={index} className="relative">
                <CardNormal product={product} priority />
              </div>
            ))}
            {
              loading && Array.from({ length: 12 }).map((_, index) => (
                <div key={index} className="relative">
                  <ProductCardSkeleton />
                </div>
              ))
            }
          </div>
        </div>
        <Paginate pageInfo={pageInfo} />
       
      </div>
    </>
  );
};

export default ProductsListingPage;
