import { useEffect, useRef, useState } from 'react'
import { ChevronDown, Search, X } from 'lucide-react'
import { useLocale } from '@meshkee/dashboard-ui'
import { useT } from '../i18n/useT'
import { isAbortError } from '../lib/api'
import { formatCellForDisplay } from '../lib/cellNumber'
import { searchCustomers, type BusinessCustomer } from '../services/customerService'
import styles from './CategorySearchSelect.module.css'

interface CustomerSearchSelectProps {
  value: BusinessCustomer | null
  onChange: (customer: BusinessCustomer | null) => void
  disabled?: boolean
  placeholder?: string
  id?: string
}

function customerLabel(customer: BusinessCustomer, withPhone = false) {
  const name = [customer.firstName, customer.lastName].filter(Boolean).join(' ').trim()
  const phone = formatCellForDisplay(customer.cellNumber)
  if (withPhone && name && phone) {
    return `${name} · ${phone}`
  }
  return name || phone
}

export function CustomerSearchSelect({
  value,
  onChange,
  disabled = false,
  placeholder,
  id,
}: CustomerSearchSelectProps) {
  const t = useT()
  const { locale } = useLocale()
  const isFa = locale === 'fa'
  const [open, setOpen] = useState(false)
  const [query, setQuery] = useState('')
  const [results, setResults] = useState<BusinessCustomer[]>([])
  const [loading, setLoading] = useState(false)
  const containerRef = useRef<HTMLDivElement>(null)

  const selectedLabel = value ? customerLabel(value, true) : ''
  const searchPlaceholder = placeholder ?? t('issueInvoice.pickCustomerPlaceholder')

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

  useEffect(() => {
    if (!open) return
    const q = query.trim()
    if (q.length < 2) {
      setResults([])
      setLoading(false)
      return
    }

    const controller = new AbortController()
    setLoading(true)
    const timer = window.setTimeout(async () => {
      try {
        const res = await searchCustomers(q, 20, controller.signal)
        setResults(res.items)
      } catch (err) {
        if (isAbortError(err)) return
        setResults([])
      } finally {
        if (!controller.signal.aborted) setLoading(false)
      }
    }, 300)

    return () => {
      window.clearTimeout(timer)
      controller.abort()
    }
  }, [query, open])

  function selectOption(customer: BusinessCustomer) {
    onChange(customer)
    setOpen(false)
    setQuery('')
  }

  return (
    <div className={styles.wrapper} ref={containerRef} dir={isFa ? 'rtl' : 'ltr'}>
      <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={value ? 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(null)}
            aria-label={t('issueInvoice.changeCustomer')}
          >
            <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">
          {query.trim().length < 2 ? (
            <li className={styles.noResults}>{t('issueInvoice.pickCustomerHint')}</li>
          ) : loading ? (
            <li className={styles.noResults}>{t('issueInvoice.loading')}</li>
          ) : results.length === 0 ? (
            <li className={styles.noResults}>{t('issueInvoice.pickCustomerNoResults')}</li>
          ) : (
            results.map((customer) => (
              <li key={customer.id}>
                <button
                  type="button"
                  className={[
                    styles.option,
                    value?.id === customer.id ? styles.optionSelected : '',
                  ]
                    .filter(Boolean)
                    .join(' ')}
                  onClick={() => selectOption(customer)}
                  role="option"
                  aria-selected={value?.id === customer.id}
                >
                  <span className={styles.optionLabel}>{customerLabel(customer)}</span>
                  <span className={styles.optionSecondary} dir="ltr">
                    {formatCellForDisplay(customer.cellNumber)}
                  </span>
                </button>
              </li>
            ))
          )}
        </ul>
      ) : null}
    </div>
  )
}
