import { ref, onUnmounted } from 'vue'
import { searchAddresses } from 'src/api/catalog'

export function useAddressSearch (form) {
  const query = ref('')
  const results = ref([])
  const searching = ref(false)
  const selected = ref(false)
  let debounce = null

  function onInput (val) {
    selected.value = false
    Object.assign(form, { address: '', city: '', postalCode: '', latitude: null, longitude: null })
    if (debounce) clearTimeout(debounce)
    if (!val || val.length < 3) { results.value = []; return }
    debounce = setTimeout(async () => {
      searching.value = true
      try { results.value = await searchAddresses(val) }
      catch { results.value = [] }
      finally { searching.value = false }
    }, 300)
  }

  function selectResult (a) {
    Object.assign(form, {
      address: a.adresse_formatee || '', city: a.nom_municipalite || '',
      postalCode: a.code_postal || '', latitude: a.latitude || null,
      longitude: a.longitude || null, province: 'QC',
    })
    query.value = a.adresse_formatee || ''
    results.value = []
    selected.value = true
  }

  function selectCustomerAddr (addr) {
    Object.assign(form, {
      address: addr.address || '', city: addr.city || '',
      postalCode: addr.postal_code || '', latitude: addr.latitude || null,
      longitude: addr.longitude || null, province: 'QC',
    })
    query.value = addr.address || ''
    selected.value = true
    results.value = []
  }

  onUnmounted(() => { if (debounce) clearTimeout(debounce) })

  return { query, results, searching, selected, onInput, selectResult, selectCustomerAddr }
}
