"use client"
import React, { useEffect } from 'react'
import graphql from 'src/utils/graphql'
import ProductCarousel from '../Carousel/ProductCarousel'
import { useTranslations } from 'next-intl'

const gql = `
query Products_connection(
    $categoryId: ID
    $brandId: ID
    $locale: I18NLocaleCode
) {
    products_connection(
        filters: {
            or: [
                { category: { documentId: { eqi: $categoryId } } }
                { brand: { documentId: { eqi: $brandId } } }
            ]
        }
        sort: ["createdAt:desc"]
        locale: $locale
    ) {
        nodes {
            documentId
            title
            price
            slug
            discount
            showPrice
            images {
                documentId
                alternativeText
                url
            }
            brand {
                title
                documentId
                image {
                    documentId
                    alternativeText
                    url
                }
                slug
            }
            category {
                documentId
                title
                slug
            }
        }
    }
}

`

const ProductRelated = ({ category, brand }) => {
  const [products, setProducts] = React.useState(null)

  const fetchProducts = async () => {
    const { products_connection: { nodes } } = await graphql(gql, {
      categoryId: brand?.documentId ? "" : category?.documentId,
      brandId: brand?.documentId ? brand?.documentId : "",
      locale: "en"
    })

    setProducts(nodes)

  }

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


  const t = useTranslations("PDP")
  return (

    <div>

      {
        products && products.length > 0 && (
          <ProductCarousel products={products} title={t("productRelated")} showMoreLink={`/products/${brand.slug}`} />
        )
      }
    </div>
  )
}

export default ProductRelated