import { useEffect, useMemo, useRef, useState } from 'react'
import { Search, X } from 'lucide-react'
import { useLocale } from '@meshkee/dashboard-ui'
import { useT } from '../i18n/useT'
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,
  disabled = false,
  minSearchLength = 3,
}: StoreItemMultiSearchSelectProps) {
  const t = useT()
  const { locale } = useLocale()
  const isFa = locale === 'fa'
  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 searchPlaceholder = placeholder ?? t('storeItems.search.minChars', { count: minSearchLength })

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

  function renderOptionMeta(option: StoreItemSearchOption) {
    const primary = isFa ? option.nameFa || option.title : option.title
    const secondary = isFa
      ? option.nameFa
        ? option.title
        : ''
      : option.nameFa

    return (
      <span className={styles.optionMeta}>
        <span
          className={isFa && option.nameFa ? styles.optionFa : styles.optionEn}
          lang={isFa && option.nameFa ? 'fa' : 'en'}
          dir={isFa ? 'rtl' : 'ltr'}
        >
          {primary}
        </span>
        {secondary ? (
          <span
            className={isFa ? styles.optionEn : `${styles.optionFa} faText`}
            lang={isFa ? 'en' : 'fa'}
            dir="rtl"
          >
            {secondary}
          </span>
        ) : null}
      </span>
    )
  }

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

  return (
    <div className={styles.wrapper} dir={isFa ? 'rtl' : 'ltr'}>
      <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={searchPlaceholder}
            value={query}
            onChange={(e) => {
              setQuery(e.target.value)
              if (!open) setOpen(true)
            }}
            onFocus={handleFocus}
            disabled={disabled}
            dir={isFa ? 'rtl' : 'ltr'}
          />
        </div>

        {showDropdown && (
          <ul className={`${selectStyles.dropdown} ${styles.dropdown}`} role="listbox">
            {filtered.length === 0 ? (
              <li className={selectStyles.noResults}>
                {options.length === 0
                  ? t('storeItems.search.noProducts')
                  : t('storeItems.search.noMatch')}
              </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>
                      {renderOptionMeta(option)}
                    </button>
                  </li>
                )
              })
            )}
          </ul>
        )}

        {open && query.trim().length > 0 && query.trim().length < minSearchLength && (
          <ul className={selectStyles.dropdown}>
            <li className={selectStyles.noResults}>
              {t('storeItems.search.minChars', { count: minSearchLength })}
            </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>
              {renderOptionMeta(option)}
              <button
                type="button"
                className={styles.removeSelectedBtn}
                onClick={() => onToggle(option.id)}
                aria-label={t('storeItems.search.clear')}
              >
                <X size={14} />
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}
