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'
import MobileView from '@/core/components/views/MobileView'
import DesktopView from '@/core/components/views/DesktopView'
import NextImage from 'next/image'
import { ChevronDownIcon } from '@heroicons/react/24/outline'
import ProductFilterDesktop from './ProductFilterDesktop'
import { useRouter } from 'next/router'

const ProductSearch = ({ query, prefixUrl, defaultBrand = null }) => {
  const router = useRouter()
  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
      }
    }
  )

  const [open, setOpen] = useState(1)
  const [order, setOrder] = useState(query?.orderBy)

  const handleOpen = (value) => {
    setOpen(open === value ? 0 : value)
  }
  const orderOptions = [
    { value: 'price-asc', label: 'Harga Terendah' },
    { value: 'price-desc', label: 'Harga Tertinggi' },
    { value: 'popular', label: 'Populer' },
    { value: 'stock', label: 'Ready Stock' }
  ]

  const handleOrderBy  = (e) => {
    let params = {
      ...router.query,
       orderBy: e.target.value
     }
     params = _.pickBy(params, _.identity)
     params = toQuery(params)
     router.push(`${prefixUrl}?${params}`)
  } 

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

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

  return (
    <>
      <MobileView>
        <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>
      </MobileView>
      <DesktopView>
        <div className='container mx-auto mt-10 flex mb-3'>
          <div className='w-3/12'>
            <ProductFilterDesktop
              brands={brands || []}
              categories={categories || []}
              prefixUrl={prefixUrl}
              defaultBrand={defaultBrand}
            />
          </div>
          <div className='w-9/12 p-3'>
            <h1 className='text-2xl mb-2 font-semibold'>Hasil Pencarian</h1>
            <div className='flex justify-between items-center mb-2'>
              <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>
              <div className='justify-end flex '>
                {/* <div>
                  <select
                    name='jumlah-baris'
                    className='form-input mt-2'
                  >
                    <option value=''>Jumlah Baris</option>
                    {orderOptions.map((option, index) => (
                      <option value={option.value}> {option.label} </option>
                    ))}
                  </select>
                </div> */}
                <div className='ml-3'>
                  <select
                    name='urutan'
                    className='form-input mt-2'
                    onChange={(e) => handleOrderBy(e)}
                  >
                    <option value=''>Urutkan</option>
                    {orderOptions.map((option, index) => (
                      <option value={option.value}> {option.label} </option>
                    ))}
                  </select>
                </div>
              </div>
            </div>
            <div className='grid grid-cols-5 gap-x-3 gap-y-6'>
              {products &&
                products.map((product) => (
                  <ProductCard
                    product={product}
                    key={product.id}
                  />
                ))}
            </div>
            <div className='flex justify-between items-center mt-6 mb-2'>
              <div className='pt-2 pb-6 flex items-center gap-x-3'>
                <NextImage
                  src='/images/logo-question.png'
                  alt='Logo Question Indoteknik'
                  width={60}
                  height={60}
                />
                <div className='text-gray_r-12/90'>
                  <span>
                    Barang yang anda cari tidak ada?{' '}
                    <a
                      href='#'
                      className='text-red_r-9'
                    >
                      Hubungi Kami
                    </a>
                  </span>
                </div>
              </div>

              <Pagination
                pageCount={pageCount}
                currentPage={parseInt(page)}
                url={`${prefixUrl}?${toQuery(_.omit(query, ['page']))}`}
                className='!justify-end'
              />
            </div>
          </div>
        </div>
      </DesktopView>
    </>
  )
}

export default ProductSearch
