import { useEffect, useMemo, 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 ProductFilterDesktop from './ProductFilterDesktop'
import { useRouter } from 'next/router'
import searchSpellApi from '@/core/api/searchSpellApi'
import Link from '@/core/components/elements/Link/Link'
import whatsappUrl from '@/core/utils/whatsappUrl'
import { Image } from '@chakra-ui/react'
import odooApi from '@/core/api/odooApi'

const ProductSearch = ({ query, prefixUrl, defaultBrand = null }) => {
  const router = useRouter()
  const { page = 1 } = query
  const [q, setQ] = useState(query?.q || '*')
  const [limit, setLimit] = useState(query?.limit || 30)
  const [orderBy, setOrderBy] = useState(router.query?.orderBy || 'popular')
  if (defaultBrand) query.brand = defaultBrand.toLowerCase()
  const { productSearch } = useProductSearch({ query: { ...query, q, limit, orderBy } })
  const [products, setProducts] = useState(null)
  const [spellings, setSpellings] = useState(null)
  const [bannerPromotionHeader, setBannerPromotionHeader] = useState(null)
  const [bannerPromotionFooter, setBannerPromotionFooter] = useState(null)
  const popup = useActive()
  const numRows = [30, 50, 80, 100]

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

  useEffect(() => {
    if (productFound == 0 && query.q && !spellings) {
      searchSpellApi({ query: query.q }).then((response) => {
        const oddIndexSuggestions = response.data.spellcheck.suggestions.filter(
          (_, index) => index % 2 === 1
        )

        const oddIndexCollations = response.data.spellcheck.collations.filter(
          (_, index) => index % 2 === 1
        )

        const dataSpellings = oddIndexSuggestions.reduce((acc, curr) => {
          oddIndexCollations.forEach((collation) => {
            acc.push(collation.collationQuery)
          })
          curr.suggestion.forEach((s) => {
            if (!acc.includes(s.word)) acc.push(s.word)
          })
          return acc
        }, [])

        if (dataSpellings.length > 0) {
          setQ(dataSpellings[0])
        }

        setSpellings(dataSpellings)
      })
    }
  }, [productFound, query, spellings])

  const brands = []
  for (
    let i = 0;
    i < productSearch.data?.facetCounts?.facetFields?.manufactureNameS.length;
    i += 2
  ) {
    const brand = productSearch.data?.facetCounts?.facetFields?.manufactureNameS[i]
    const qty = productSearch.data?.facetCounts?.facetFields?.manufactureNameS[i + 1]
    if (qty > 0) {
      brands.push({ brand, qty })
    }
  }
  /*const brandsList = productSearch.data?.facetCounts?.facetFields?.manufactureName?.filter(
    (value, index) => {
      if (index % 2 === 0) {
        const brand = value
        const qty = index + 1
        brands.push({ brand, qty })
      }
    }
  )*/

  const categories = []
  for (let i = 0; i < productSearch.data?.facetCounts?.facetFields?.categoryName.length; i += 2) {
    const name = productSearch.data?.facetCounts?.facetFields?.categoryName[i]
    const qty = productSearch.data?.facetCounts?.facetFields?.categoryName[i + 1]
    if (qty > 0) {
      categories.push({ name, qty })
    }
  }
  
  /*const categories = productSearch.data?.facetCounts?.facetFields?.categoryName?.filter(
    (value, index) => {
      if (index % 2 === 0) {
        return true
      }
    }
  )*/

  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}`)
  }

  const handleLimit = (e) => {
    let params = {
      ...router.query,
      limit: e.target.value
    }
    params = _.pickBy(params, _.identity)
    params = toQuery(params)
    router.push(`${prefixUrl}?${params}`)
  }
  const getBanner = async () => {
    if (router.pathname.includes('search')) {
      const getBannerHeader = await odooApi('GET', '/api/v1/banner?type=promotion-header')
      const getBannerFooter = await odooApi('GET', '/api/v1/banner?type=promotion-footer')
      var randomIndex = Math.floor(Math.random() * getBannerHeader.length)
      var randomIndexFooter = Math.floor(Math.random() * getBannerFooter.length)
      setBannerPromotionHeader(getBannerHeader[randomIndex])
      setBannerPromotionFooter(getBannerFooter[randomIndexFooter])
    }
  }

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

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

  const SpellingComponent = useMemo(() => {
    return (
      <>
        Mungkin yang anda cari{' '}
        {spellings?.map((spelling, i) => (
          <Link href={`/shop/search?q=${spelling}`} key={i} className='inline'>
            {spelling}
            {i + 1 < spellings.length ? ', ' : ''}
          </Link>
        ))}
      </>
    )
  }, [spellings])

  return (
    <>
      <MobileView>
        {productSearch.isLoading && <ProductSearchSkeleton />}
        <div className='p-4 pt-0'>
          <h1 className='mb-2 font-semibold text-h-sm'>Produk</h1>

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

          {productFound > 0 && (
            <div className='flex items-center gap-x-2 mb-5 justify-between'>
              <div>
                <button className='btn-light py-2 px-5 h-[40px]' onClick={popup.activate}>
                  Filter
                </button>
              </div>
              <div className=''>
                <select
                  name='limit'
                  className='form-input w-24'
                  value={router.query?.limit || ''}
                  onChange={(e) => handleLimit(e)}
                >
                  {numRows.map((option, index) => (
                    <option key={index} value={option}>
                      {' '}
                      {option}{' '}
                    </option>
                  ))}
                </select>
              </div>
            </div>
          )}

          <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 flex mb-3'>
          <div className='w-3/12'>
            <ProductFilterDesktop
              brands={brands || []}
              categories={categories || []}
              prefixUrl={prefixUrl}
              defaultBrand={defaultBrand}
            />
          </div>
          <div className='w-9/12 pl-6'>
            {bannerPromotionHeader && bannerPromotionHeader?.image && (
              <div className='mb-3'>
                <Image
                  src={bannerPromotionHeader?.image}
                  alt=''
                  className='object-cover object-center h-full mx-auto'
                />
              </div>
            )}

            <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'>
                {!spellings ? (
                  <>
                    Menampilkan&nbsp;
                    {pageCount > 1 ? (
                      <>
                        {productStart + 1}-
                        {parseInt(productStart) + parseInt(productRows) > productFound
                          ? productFound
                          : parseInt(productStart) + parseInt(productRows)}
                        &nbsp;dari&nbsp;
                      </>
                    ) : (
                      ''
                    )}
                    {productFound}
                    &nbsp;produk{' '}
                    {query.q && (
                      <>
                        untuk pencarian <span className='font-semibold'>{query.q}</span>
                      </>
                    )}
                  </>
                ) : (
                  SpellingComponent
                )}
              </div>
              <div className='justify-end flex '>
                <div className='ml-3'>
                  <select
                    name='urutan'
                    className='form-input mt-2'
                    value={orderBy}
                    onChange={(e) => handleOrderBy(e)}
                  >
                    {orderOptions.map((option, index) => (
                      <option key={index} value={option.value}>
                        {' '}
                        {option.label}{' '}
                      </option>
                    ))}
                  </select>
                </div>
                <div className='ml-3'>
                  <select
                    name='limit'
                    className='form-input mt-2'
                    value={router.query?.limit || ''}
                    onChange={(e) => handleLimit(e)}
                  >
                    {numRows.map((option, index) => (
                      <option key={index} value={option}>
                        {' '}
                        {option}{' '}
                      </option>
                    ))}
                  </select>
                </div>
              </div>
            </div>
            {productSearch.isLoading && <ProductSearchSkeleton />}
            <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={
                        query?.q
                          ? whatsappUrl('productSearch', {
                              name: query.q
                            })
                          : whatsappUrl()
                      }
                      className='text-danger-500'
                    >
                      Hubungi Kami
                    </a>
                  </span>
                </div>
              </div>

              <Pagination
                pageCount={pageCount}
                currentPage={parseInt(page)}
                url={`${prefixUrl}?${toQuery(_.omit(query, ['page']))}`}
                className='!justify-end'
              />
            </div>
            {bannerPromotionFooter && bannerPromotionFooter?.image && (
              <div className='mb-3'>
                <Image
                  src={bannerPromotionFooter?.image}
                  alt=''
                  className='object-cover object-center h-full mx-auto'
                />
              </div>
            )}
          </div>
        </div>
      </DesktopView>
    </>
  )
}

export default ProductSearch
