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

interface SearchableSelectProps {
  options: FlatCategory[]
  value: string
  onChange: (value: string) => void
  placeholder?: string
}

export function SearchableSelect({
  options,
  value,
  onChange,
  placeholder = 'Search categories...',
}: SearchableSelectProps) {
  const [open, setOpen] = useState(false)
  const [query, setQuery] = useState('')
  const containerRef = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLInputElement>(null)

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

  const filtered = options.filter((cat) => {
    const q = query.trim().toLowerCase()
    if (!q) return true
    return (
      cat.nameEn.toLowerCase().includes(q) ||
      cat.nameFa.includes(query.trim())
    )
  })

  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() {
    setOpen(true)
  }

  return (
    <div className={styles.wrapper} ref={containerRef}>
      <div className={`${styles.inputWrap} ${open ? styles.inputWrapOpen : ''}`}>
        <Search size={16} className={styles.searchIcon} />
        <input
          ref={inputRef}
          type="text"
          className={styles.input}
          placeholder={selected ? `${selected.nameEn} / ${selected.nameFa}` : placeholder}
          value={open ? query : selected ? `${selected.nameEn} / ${selected.nameFa}` : ''}
          onChange={(e) => {
            setQuery(e.target.value)
            if (!open) setOpen(true)
          }}
          onFocus={handleFocus}
        />
        {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>

      {open && (
        <ul className={styles.dropdown} role="listbox">
          <li>
            <button
              type="button"
              className={`${styles.option} ${value === '' ? styles.optionSelected : ''}`}
              onClick={() => selectOption('')}
            >
              — None (root category) —
            </button>
          </li>
          {filtered.length === 0 ? (
            <li className={styles.noResults}>No categories found</li>
          ) : (
            filtered.map((cat) => (
              <li key={cat.id}>
                <button
                  type="button"
                  className={`${styles.option} ${value === cat.id ? styles.optionSelected : ''}`}
                  style={{ paddingLeft: `${14 + cat.depth * 16}px` }}
                  onClick={() => selectOption(cat.id)}
                >
                  <span className={styles.optionEn}>{cat.nameEn}</span>
                  <span className={styles.optionSep}>·</span>
                  <span className={styles.optionFa}>{cat.nameFa}</span>
                </button>
              </li>
            ))
          )}
        </ul>
      )}
    </div>
  )
}
