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

export interface StoreItemSearchOption {
  id: string
  title: string
  nameFa: string
  image: string | null
}

interface StoreItemMultiSearchSelectProps {
  options: StoreItemSearchOption[]
  selectedIds: string[]
  onToggle: (id: string) => void
  placeholder?: string
  disabled?: boolean
  minSearchLength?: number
}

export function StoreItemMultiSearchSelect({
  options,
  selectedIds,
  onToggle,
  placeholder = 'Type 3+ characters to search store items',
  disabled = false,
  minSearchLength = 3,
}: StoreItemMultiSearchSelectProps) {
  const [open, setOpen] = useState(false)
  const [query, setQuery] = useState('')
  const containerRef = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLInputElement>(null)

  const selectedSet = useMemo(() => new Set(selectedIds), [selectedIds])

  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])

  const selectedOptions = useMemo(
    () => options.filter((option) => selectedSet.has(option.id)),
    [options, selectedSet],
  )

  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 handleFocus() {
    if (!disabled) setOpen(true)
  }

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

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

        {showDropdown && (
          <ul className={`${selectStyles.dropdown} ${styles.dropdown}`} role="listbox">
            {filtered.length === 0 ? (
              <li className={selectStyles.noResults}>
                {options.length === 0 ? 'No store items available.' : 'No matching store items.'}
              </li>
            ) : (
              filtered.map((option) => {
                const checked = selectedSet.has(option.id)
                return (
                  <li key={option.id}>
                    <button
                      type="button"
                      role="option"
                      aria-selected={checked}
                      className={`${styles.option} ${checked ? styles.optionSelected : ''}`}
                      onClick={() => onToggle(option.id)}
                    >
                      <span className={styles.checkbox} aria-hidden="true">
                        {checked ? '✓' : ''}
                      </span>
                      <span className={styles.thumb}>
                        {option.image ? (
                          <img src={option.image} alt="" loading="lazy" />
                        ) : (
                          <span className={styles.thumbPlaceholder} />
                        )}
                      </span>
                      <span className={styles.optionMeta}>
                        <span className={styles.optionEn}>{option.title}</span>
                        {option.nameFa && <span className={`${styles.optionFa} faText`}>{option.nameFa}</span>}
                      </span>
                    </button>
                  </li>
                )
              })
            )}
          </ul>
        )}

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

      {selectedOptions.length > 0 && (
        <div className={styles.selectedList}>
          {selectedOptions.map((option) => (
            <div key={option.id} className={styles.selectedRow}>
              <span className={styles.thumb}>
                {option.image ? (
                  <img src={option.image} alt="" loading="lazy" />
                ) : (
                  <span className={styles.thumbPlaceholder} />
                )}
              </span>
              <div className={styles.optionMeta}>
                <span className={styles.optionEn}>{option.title}</span>
                {option.nameFa && <span className={`${styles.optionFa} faText`}>{option.nameFa}</span>}
              </div>
              <button
                type="button"
                className={styles.removeSelectedBtn}
                onClick={() => onToggle(option.id)}
                aria-label={`Remove ${option.title}`}
              >
                <X size={14} />
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
