import { useEffect, useRef, useState } from 'react'
import { ChevronDown, Search, X } from 'lucide-react'
import {
  getLocationOptionLabel,
  useLocale,
  type CityOption,
} from '@meshkee/dashboard-ui'
import { useT } from '../i18n/useT'
import styles from './CitySearchSelect.module.css'

interface CitySearchSelectProps {
  options: CityOption[]
  value: string
  onChange: (value: string) => void
  disabled?: boolean
  placeholder?: string
  id?: string
}

export function CitySearchSelect({
  options,
  value,
  onChange,
  disabled = false,
  placeholder,
  id,
}: CitySearchSelectProps) {
  const t = useT()
  const { locale } = useLocale()
  const [open, setOpen] = useState(false)
  const [query, setQuery] = useState('')
  const containerRef = useRef<HTMLDivElement>(null)

  const selected = options.find((option) => option.id === value)
  const selectedLabel = selected ? getLocationOptionLabel(selected, locale) : ''
  const searchPlaceholder = placeholder ?? t('customerProducts.form.fields.searchCity')

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

  useEffect(() => {
    if (!open) return

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

  useEffect(() => {
    if (disabled) {
      setOpen(false)
      setQuery('')
    }
  }, [disabled])

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

  return (
    <div className={styles.wrapper} ref={containerRef}>
      <div
        className={[
          styles.inputWrap,
          open ? styles.inputWrapOpen : '',
          disabled ? styles.inputWrapDisabled : '',
        ]
          .filter(Boolean)
          .join(' ')}
      >
        <Search size={16} className={styles.searchIcon} aria-hidden />
        <input
          id={id}
          type="text"
          className={styles.input}
          disabled={disabled}
          placeholder={selected ? selectedLabel : searchPlaceholder}
          value={open ? query : selectedLabel}
          onChange={(e) => {
            setQuery(e.target.value)
            if (!open) setOpen(true)
          }}
          onFocus={() => {
            if (!disabled) setOpen(true)
          }}
          autoComplete="off"
          role="combobox"
          aria-expanded={open}
          aria-autocomplete="list"
        />
        {value && !open && !disabled ? (
          <button
            type="button"
            className={styles.clearBtn}
            onClick={() => onChange('')}
            aria-label={t('customerProducts.form.fields.clearCity')}
          >
            <X size={14} />
          </button>
        ) : null}
        <ChevronDown
          size={16}
          className={`${styles.chevron} ${open ? styles.chevronOpen : ''}`}
          aria-hidden
        />
      </div>

      {open && !disabled ? (
        <ul className={styles.dropdown} role="listbox">
          {filtered.length === 0 ? (
            <li className={styles.noResults}>{t('customerProducts.form.fields.noCities')}</li>
          ) : (
            filtered.map((option) => (
              <li key={option.id}>
                <button
                  type="button"
                  className={`${styles.option} ${value === option.id ? styles.optionSelected : ''}`}
                  onClick={() => selectOption(option.id)}
                  role="option"
                  aria-selected={value === option.id}
                >
                  {getLocationOptionLabel(option, locale)}
                </button>
              </li>
            ))
          )}
        </ul>
      ) : null}
    </div>
  )
}
