'use client'

import React, { useEffect, useMemo, useRef } from 'react'
import { LuSearch } from 'react-icons/lu'

interface ComboboxProps<OptionType> {
  showDropdown: boolean
  searchValue: string
  placeholderText?: string
  inputRef: React.RefObject<HTMLInputElement>
  isLoading: boolean
  filteredOptions: OptionType[]
  selectedOption?: OptionType
  options: OptionType[]
  hasMore?: boolean
  isLoadingMore?: boolean
  renderNoResultsFound?: () => React.ReactNode
  renderOption?: (option: OptionType, index: number) => React.ReactNode
  renderSkeletonComponent?: () => React.ReactNode
  handleSelectOption: (option: OptionType) => void
  handleSearch: (event: React.ChangeEvent<HTMLInputElement>) => void
  onLoadMore?: () => void
  renderLoadingMore?: () => React.ReactNode
}

const Combobox = <OptionType,>({
  showDropdown,
  searchValue,
  placeholderText,
  inputRef,
  isLoading,
  filteredOptions,
  hasMore = false,
  isLoadingMore = false,
  renderNoResultsFound,
  renderOption,
  renderSkeletonComponent,
  handleSearch,
  onLoadMore,
  renderLoadingMore,
}: ComboboxProps<OptionType>) => {
  const listRef = useRef<HTMLDivElement>(null)
  const sentinelRef = useRef<HTMLDivElement>(null)

  const supportsInfiniteScroll = useMemo(() => !!onLoadMore, [onLoadMore])

  // IntersectionObserver on sentinel for infinite scroll
  useEffect(() => {
    if (
      !supportsInfiniteScroll ||
      !sentinelRef.current ||
      !hasMore ||
      !showDropdown
    ) {
      return
    }

    const el = sentinelRef.current
    const root = listRef.current

    const io = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && !isLoadingMore) {
          onLoadMore?.()
        }
      },
      { root, rootMargin: '100px 0px' },
    )

    io.observe(el)
    return () => io.unobserve(el)
  }, [supportsInfiniteScroll, hasMore, isLoadingMore, onLoadMore, showDropdown])

  return (
    <div
      className={`absolute z-20 transition-all duration-100 w-full ease-out top-full mt-1 ${showDropdown ? 'opacity-100' : 'opacity-0 invisible'}`}
    >
      <div className="bg-white rounded-lg shadow-lg w-full max-h-64 overflow-hidden border border-gray-200">
        <div className="p-3 border-b border-gray-200">
          {/* Search Box */}
          <div className="relative">
            <LuSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
            <input
              type="text"
              placeholder={placeholderText || 'Search...'}
              value={searchValue}
              ref={inputRef}
              onChange={handleSearch}
              className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-1 focus:ring-blue-800 focus:border-blue-800 hover:border-blue-800 text-sm"
            />
          </div>
        </div>

        {/* Options */}
        <div ref={listRef} className="overflow-y-auto max-h-48">
          {isLoading ? (
            renderSkeletonComponent?.()
          ) : filteredOptions?.length ? (
            <>
              {filteredOptions.map((option, index) =>
                renderOption?.(option, index),
              )}

              {/* Sentinel for infinite scroll */}
              {supportsInfiniteScroll && hasMore && (
                <div
                  ref={sentinelRef}
                  className="px-4 py-2 text-center text-xs text-gray-400"
                >
                  {isLoadingMore
                    ? (renderLoadingMore?.() ?? 'Loading more...')
                    : ''}
                </div>
              )}
            </>
          ) : (
            renderNoResultsFound?.()
          )}
        </div>
      </div>
    </div>
  )
}

export default Combobox
