import { computed, defineComponent } from 'vue'
import { TypeAheadSmartMultiple, Filter } from '../typeahead-smart-multiple'
import { AutocompleteCaminoFiltres, caminoAutocompleteFiltres } from './camino-filtres'
import { Entreprise } from 'camino-common/src/entreprise'
import { ApiClient } from '../../../api/api-client'
import { TitreId } from 'camino-common/src/validators/titres'
import { caminoFiltres } from 'camino-common/src/filters'
import { AdministrationId, sortedAdministrations } from 'camino-common/src/static/administrations'
import { isNotNullNorUndefined } from 'camino-common/src/typescript-tools'

export type InputAutocompleteValues = (typeof caminoFiltres)[AutocompleteCaminoFiltres]['validator']['_output']
type Props = {
  id: string
  filter: AutocompleteCaminoFiltres
  initialValue: InputAutocompleteValues
  entreprises: Entreprise[]
  onFilterAutocomplete: (values: InputAutocompleteValues) => void
  apiClient: Pick<ApiClient, 'titresRechercherByNom' | 'getTitresByIds'>
}

export const InputAutocomplete = defineComponent<Props>(props => {
  const filter = computed<(typeof caminoAutocompleteFiltres)[number]>(() => {
    return caminoFiltres[props.filter]
  })
  const filterFull = computed(() => {
    const filterCopy = { ...filter.value }
    if (filterCopy.id === 'entreprisesIds') {
      filterCopy.elements = props.entreprises
    }

    const filterFull: Filter<(typeof filter.value)['id']> = {
      ...filterCopy,
      // @ts-ignore typescript est perdu ici (probablement un distributive qu'il faut supprimer)
      value: props.initialValue,
    }
    if (filterCopy.id === 'titresIds') {
      const filterTitresIds = filterFull as Filter<TitreId>
      if (filterTitresIds.lazy) {
        filterTitresIds.search = async (value: string) => {
          try {
            return await props.apiClient.titresRechercherByNom(value)
          } catch (e) {
            console.error('error', e)

            return Promise.resolve({ elements: [] })
          }
        }
        filterTitresIds.load = async (value: TitreId[]) => {
          try {
            return await props.apiClient.getTitresByIds(value, 'filter-input-autocomplete')
          } catch (e) {
            console.error('error', e)

            return Promise.resolve({ elements: [] })
          }
        }
      }
    }
    if (filterCopy.id === 'administrationIds') {
      // TODO 2025-03-12 là on n'a pas un lien correct entre le type de filterFull et Filter. On ne sait pas de quel type (AdministrationId) est le filter administrationIds
      const filterAdministrationIds = filterFull as unknown as Filter<AdministrationId>
      if (filterAdministrationIds.lazy) {
        filterAdministrationIds.search = async (value: string) => {
          const lignes = [...sortedAdministrations].filter(a => {
            if (isNotNullNorUndefined(value) && value !== '') {
              if (!a.id.toLowerCase().includes(value.toLowerCase()) && !a.nom.toLowerCase().includes(value.toLowerCase()) && !a.abreviation.toLowerCase().includes(value.toLowerCase())) {
                return false
              }
            }

            return true
          })

          return Promise.resolve({ elements: lignes })
        }
        filterAdministrationIds.load = async _value => {
          return Promise.resolve({ elements: [...sortedAdministrations] })
        }
      }
    }

    return filterFull
  })

  const onSelectItems = (items: { id: string }[]) => {
    // @ts-ignore typescript est perdu ici (probablement un distributive qu'il faut supprimer)
    props.onFilterAutocomplete(items.map(({ id }) => id))
  }

  return () => <TypeAheadSmartMultiple id={props.id} filter={filterFull.value} onSelectItems={onSelectItems} />
})

// @ts-ignore waiting for https://github.com/vuejs/core/issues/7833
InputAutocomplete.props = ['filter', 'entreprises', 'initialValue', 'onFilterAutocomplete', 'apiClient', 'id']
