import searchSuggestApi from '@/core/api/searchSuggestApi'
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline'
import { useCallback, useEffect, useRef, useState } from 'react'
import Link from '../Link/Link'
import { useRouter } from 'next/router'
import { getIdFromSlug, getNameFromSlug } from '@/core/utils/slug'

const Search = () => {
  const router = useRouter()
  const queryRef = useRef()
  const { slug = '' } = router.query
  const [query, setQuery] = useState(router.query.q || '')
  const [suggestions, setSuggestions] = useState([])
  const [segment, setSegment] = useState(null)
  const [optionSegment, setOptionSegment] = useState(null)
  const [optoinSelected, setOptionSelected] = useState(getNameFromSlug(slug) || 'default')
  const [pathSegments, setPathSegments] = useState(router?.asPath.split('/') || [])

  const loadSuggestion = useCallback(() => {
    if (query && document.activeElement == queryRef.current) {
      searchSuggestApi({ query }).then((response) => {
        setSuggestions(response.data?.suggestions || [])
      })
    } else {
      setSuggestions([])
    }
  }, [query])

  useEffect(() => {
    if (query && document.activeElement == queryRef.current) {
      loadSuggestion()
    } else {
      setSuggestions([])
    }
    setFilterSearch()
  }, [loadSuggestion, query])

  const handleSubmit = (e) => {
    e.preventDefault()
    if (optionSegment && optoinSelected !== 'default' && optoinSelected) {
      router.push(`/shop/${segment}/${slug}?q=${query}`)
    } else {
      if (query) {
        router.push(`/shop/search?q=${query}`)
      } else {
        queryRef.current.focus()
      }
    }
  }

  const handleSelectChange = async (e) => {
    await setOptionSelected(e.target.value)
  }
  const setFilterSearch = async () => {
    if (router.pathname.includes('brands') && pathSegments[3]) {
      await setSegment(pathSegments[2])
      await setOptionSegment(getNameFromSlug(slug))
    }
  }

  const onInputBlur = () => {
    setTimeout(() => {
      setSuggestions([])
    }, 100)
  }

  return (
    <>
      <form onSubmit={handleSubmit} className='flex-1 flex relative'>
        {segment && (
          <select
            value={optoinSelected}
            onChange={handleSelectChange}
            className='form-select p-3 rounded-l-sm bg-white border border-gray_r-6 border-r-0 capitalize'
          >
            <option value='default'>Di Indoteknik</option>
            <option value={optionSegment}>Di {optionSegment}</option>
          </select>
        )}

        <input
          type='text'
          ref={queryRef}
          className={`form-input p-3 ${
            segment ? 'rounded-l-none border-l-0' : ''
          } rounded-r-none border-r-0 focus:border-gray_r-6`}
          placeholder='Ketik nama, part number, merk'
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          onBlur={onInputBlur}
          onFocus={loadSuggestion}
        />
        <button
          type='submit'
          aria-label='SearchButton'
          className='rounded-r border border-l-0 border-gray_r-6 px-2'
        >
          <MagnifyingGlassIcon className='w-6' />
        </button>

        <div
          className={`absolute w-full top-[50px] rounded-b bg-gray_r-1 border border-gray_r-6 divide-y divide-gray_r-6 z-50 ${
            suggestions.length > 0 ? 'block' : 'hidden'
          }`}
        >
          {suggestions.map((suggestion, index) => (
            <Link
              href={`/shop/search?q=${suggestion.term}`}
              key={index}
              className='px-3 py-3 !text-gray_r-12 font-normal'
            >
              {suggestion.term}
            </Link>
          ))}
        </div>
      </form>
    </>
  )
}

export default Search
