import { useEffect, useState } from 'react'
import useProductSearch from '../hooks/useProductSearch'
import ProductCard from './ProductCard'
import Pagination from '@/core/components/elements/Pagination/Pagination'
import { toQuery } from 'lodash-contrib'
import _ from 'lodash'
import ProductSearchSkeleton from './Skeleton/ProductSearchSkeleton'
import ProductFilter from './ProductFilter'
import useActive from '@/core/hooks/useActive'

const ProductSearch = ({ query, prefixUrl, defaultBrand = null }) => {
  const { page = 1 } = query
  if (defaultBrand) query.brand = defaultBrand.toLowerCase()
  const { productSearch } = useProductSearch({ query })
  const [products, setProducts] = useState(null)
  const popup = useActive()

  const pageCount = Math.ceil(
    productSearch.data?.response.numFound / productSearch.data?.responseHeader.params.rows
  )
  const productStart = productSearch.data?.responseHeader.params.start
  const productRows = productSearch.data?.responseHeader.params.rows
  const productFound = productSearch.data?.response.numFound

  const brands = productSearch.data?.facetCounts?.facetFields?.brandStr?.filter((value, index) => {
    if (index % 2 === 0) {
      return true
    }
  })
  const categories = productSearch.data?.facetCounts?.facetFields?.categoryNameStr?.filter(
    (value, index) => {
      if (index % 2 === 0) {
        return true
      }
    }
  )

  useEffect(() => {
    if (!products) {
      setProducts(productSearch.data?.response?.products)
    }
  }, [query, products, productSearch])

  if (productSearch.isLoading) {
    return <ProductSearchSkeleton />
  }

  return (
    <div className='p-4'>
      <h1 className='mb-2 font-semibold text-h-sm'>Produk</h1>

      <div className='mb-2 leading-6 text-gray_r-11'>
        {productFound > 0 ? (
          <>
            Menampilkan&nbsp;
            {pageCount > 1 ? (
              <>
                {productStart + 1}-
                {productStart + productRows > productFound
                  ? productFound
                  : productStart + productRows}
                &nbsp;dari&nbsp;
              </>
            ) : (
              ''
            )}
            {productFound}
            &nbsp;produk{' '}
            {query.q && (
              <>
                untuk pencarian <span className='font-semibold'>{query.q}</span>
              </>
            )}
          </>
        ) : (
          'Mungkin yang anda cari'
        )}
      </div>

      <button className='btn-light mb-6 py-2 px-5' onClick={popup.activate}>
        Filter
      </button>

      <div className='grid grid-cols-2 gap-3'>
        {products && products.map((product) => <ProductCard product={product} key={product.id} />)}
      </div>

      <Pagination
        pageCount={pageCount}
        currentPage={parseInt(page)}
        url={`${prefixUrl}?${toQuery(_.omit(query, ['page']))}`}
        className='mt-6 mb-2'
      />

      <ProductFilter
        active={popup.active}
        close={popup.deactivate}
        brands={brands || []}
        categories={categories || []}
        prefixUrl={prefixUrl}
        defaultBrand={defaultBrand}
      />
    </div>
  )
}

export default ProductSearch
