import { useEffect, useMemo, useRef, useState } from 'react'
import { ChevronDown, Search, X } from 'lucide-react'
import styles from './SearchableSelect.module.css'

export interface ProductSearchOption {
  id: string
  title: string
  nameFa: string
}

interface ProductSearchSelectProps {
  options: ProductSearchOption[]
  value: string
  onChange: (value: string) => void
  placeholder?: string
  disabled?: boolean
  id?: string
  minSearchLength?: number
}

export function ProductSearchSelect({
  options,
  value,
  onChange,
  placeholder = 'Search products...',
  disabled = false,
  id,
  minSearchLength = 3,
}: ProductSearchSelectProps) {
  const [open, setOpen] = useState(false)
  const [query, setQuery] = useState('')
  const containerRef = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLInputElement>(null)

  const selected = options.find((option) => option.id === value)

  const filtered = useMemo(() => {
    const trimmed = query.trim()
    if (trimmed.length < minSearchLength) return []
    const q = trimmed.toLowerCase()
    return options.filter(
      (option) =>
        option.title.toLowerCase().includes(q) ||
        option.nameFa.includes(trimmed),
    )
  }, [options, query, minSearchLength])

  useEffect(() => {
    if (!open) return
    const onClickOutside = (e: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setOpen(false)
        setQuery('')
      }
    }
    document.addEventListener('mousedown', onClickOutside)
    return () => document.removeEventListener('mousedown', onClickOutside)
  }, [open])

  function selectOption(id: string) {
    onChange(id)
    setOpen(false)
    setQuery('')
  }

  function handleFocus() {
    if (!disabled) setOpen(true)
  }

  const showDropdown = open && query.trim().length >= minSearchLength

  return (
    <div className={styles.wrapper} ref={containerRef}>
      <div className={`${styles.inputWrap} ${open ? styles.inputWrapOpen : ''}`}>
        <Search size={16} className={styles.searchIcon} />
        <input
          ref={inputRef}
          id={id}
          type="text"
          className={styles.input}
          placeholder={
            selected
              ? `${selected.title}${selected.nameFa ? ` / ${selected.nameFa}` : ''}`
              : placeholder
          }
          value={open ? query : selected ? `${selected.title}${selected.nameFa ? ` / ${selected.nameFa}` : ''}` : ''}
          onChange={(e) => {
            setQuery(e.target.value)
            if (!open) setOpen(true)
            if (value) onChange('')
          }}
          onFocus={handleFocus}
          disabled={disabled}
        />
        {value && !open && (
          <button
            type="button"
            className={styles.clearBtn}
            onClick={() => onChange('')}
            aria-label="Clear selection"
          >
            <X size={14} />
          </button>
        )}
        <ChevronDown size={16} className={`${styles.chevron} ${open ? styles.chevronOpen : ''}`} />
      </div>

      {showDropdown && (
        <ul className={styles.dropdown} role="listbox">
          {filtered.length === 0 ? (
            <li className={styles.noResults}>
              {options.length === 0 ? 'No products available.' : 'No matching products.'}
            </li>
          ) : (
            filtered.map((option) => (
              <li key={option.id}>
                <button
                  type="button"
                  role="option"
                  aria-selected={option.id === value}
                  className={`${styles.option} ${option.id === value ? styles.optionSelected : ''}`}
                  onClick={() => selectOption(option.id)}
                >
                  <span className={styles.optionEn}>{option.title}</span>
                  {option.nameFa && (
                    <>
                      <span className={styles.optionSep}>/</span>
                      <span className={styles.optionFa}>{option.nameFa}</span>
                    </>
                  )}
                </button>
              </li>
            ))
          )}
        </ul>
      )}

      {open && query.trim().length > 0 && query.trim().length < minSearchLength && (
        <ul className={styles.dropdown}>
          <li className={styles.noResults}>Type at least {minSearchLength} characters to search</li>
        </ul>
      )}
    </div>
  )
}
