<script setup>
import HumanName from './HumanName.vue'

const delay = ref(null)
delay.value = 10

async function getItemsSearch(query, el$) {
  const { data } = await useFetch('/api/address?search=' + query, {
    lazy: true,
    server: false,
  })
  return data.value.map((d) => {
    return {
      value: d,
      label: d.display,
    }
  })
  // const addressesString = data.value.map((value) => {
  //   var result = value.villages ? 'Desa/Kel ' + value.villages + ', ' : ''
  //   result += value.districts ? 'Kec ' + value.districts + ', ' : ''
  //   result += value.cities ? 'Kota/Kab ' + value.cities + ', ' : ''
  //   result += value.states ? 'Prov ' + value.states + ', ' : ''
  //   result += value.countries ? value.countries : ''
  //   return { value: value, label: result }
  // })
  // return addressesString
}

async function getPostal(query) {
  const { data } = await useFetch('/api/address?search=' + query, {
    lazy: true,
    server: false,
  })
  return data.value
}

function onSelectSearch(option, el$) {
  const postal = getPostal(option.value.states.regencies.districts)
  el$.$parent.$parent.children$.country.update(option.value)
  el$.$parent.$parent.children$.state.update(option.value.states)
  el$.$parent.$parent.children$.city.update(option.value.states.regencies)
  el$.$parent.$parent.children$.district.update(
    option.value.states.regencies.districts,
  )
  el$.$parent.$parent.children$.village.update(
    option.value.states.regencies.districts.villages,
  )
  el$.$parent.$parent.children$.postalCode.update(postal[0])
}

function onSelectCountry(option, el$) {
  el$.$parent.$parent.children$.state.clear()
  el$.$parent.$parent.children$.city.clear()
  el$.$parent.$parent.children$.district.clear()
  el$.$parent.$parent.children$.village.clear()
  el$.$parent.$parent.children$.postalCode.clear()
}

function onSelectState(option, el$) {
  el$.$parent.$parent.children$.city.clear()
  el$.$parent.$parent.children$.district.clear()
  el$.$parent.$parent.children$.village.clear()
  el$.$parent.$parent.children$.postalCode.clear()
}

function onSelectCity(option, el$) {
  el$.$parent.$parent.children$.district.clear()
  el$.$parent.$parent.children$.village.clear()
  el$.$parent.$parent.children$.postalCode.clear()
}

function onSelectDistrict(option, el$) {
  el$.$parent.$parent.children$.village.clear()
  el$.$parent.$parent.children$.postalCode.clear()
  console.log(el$)
}

function onSelectVillage(option, el$) {
  el$.$parent.$parent.children$.postalCode.clear()
}

async function onChange(input, el$) {
  delay.value = input.length > 0 ? 5000 : 10
}

function formatData(name, value) {
  return { [name]: value.name }
}
function formatLine(name, value) {
  return { [name]: value.split('\n') }
}
</script>
<template>
  <ListElement name="address">
    <template #default="{ index }">
      <ObjectElement :name="index" :columns="{
        sm: {
          container: 12,
        },
      }">
        <TextareaElement name="line" placeholder="Alamat" :format-data="formatLine" />
        <SelectElement name="search" @select="onSelectSearch" :search="true" :native="false" input-type="search"
          autocomplete="off" placeholder="🔎 Cari Alamat" :resolve-on-load="false" :delay="20" :items="getItemsSearch"
          :submit="false" no-results-text="Alamat Tidak Ditemukan" :object="true" :filter-results="false"
          :caret="false" />
        <SelectElement name="country" allow-absent @select="onSelectCountry" items="/api/address/countries"
          :format-data="formatData" :search="true" :native="false" :object="true" :resolve-on-load="true"
          autocomplete="on" value-prop="_id" label-prop="name" input-type="search" placeholder="Negara" :conditions="[
            [
              ['address.*.line', 'not_empty'],
              ['address.*.search', 'not_empty'],
            ],
          ]" :columns="{
            sm: {
              container: 6,
            },
          }" />
        <SelectElement name="state" allow-absent @select="onSelectState" @search-change="onChange"
          items="/api/address/states?parent={address.*.country}" :format-data="formatData" :search="true"
          :native="false" :object="true" :delay="delay" :resolve-on-load="false" autocomplete="on" value-prop="_id"
          label-prop="name" input-type="search" placeholder="Provinsi"
          :conditions="[['address.*.country', 'not_empty']]" :columns="{
            sm: {
              container: 6,
            },
          }" />
        <SelectElement name="city" allow-absent @select="onSelectCity" @search-change="onChange"
          items="/api/address/cities?parent={address.*.state}" :format-data="formatData" :search="true" :native="false"
          :object="true" :delay="delay" :resolve-on-load="false" autocomplete="on" value-prop="_id" label-prop="name"
          input-type="search" placeholder="Kota / Kabupaten" :conditions="[['address.*.state', 'not_empty']]" :columns="{
            sm: {
              container: 6,
            },
          }" />
        <SelectElement name="district" allow-absent @select="onSelectDistrict" @search-change="onChange"
          items="/api/address/districts?parent={address.*.city}" :format-data="formatData" :search="true"
          :native="false" :object="true" :delay="delay" :resolve-on-load="false" autocomplete="on" value-prop="_id"
          label-prop="name" input-type="search" placeholder="Kecamatan" :conditions="[['address.*.city', 'not_empty']]"
          :columns="{
            sm: {
              container: 6,
            },
          }" />
        <SelectElement name="village" allow-absent @select="onSelectVillage" @search-change="onChange"
          items="/api/address/villages?parent={address.*.district}" :format-data="formatData" :search="true"
          :native="false" :object="true" :delay="delay" :resolve-on-load="false" autocomplete="on" value-prop="_id"
          label-prop="name" input-type="search" placeholder="Desa / Kelurahan"
          :conditions="[['address.*.district', 'not_empty']]" :columns="{
            sm: {
              container: 6,
            },
          }" />
        <SelectElement name="postalCode" allow-absent @search-change="onChange"
          items="/api/address/postal?parent={address.*.district}" :native="false" :object="false" :delay="delay"
          :resolve-on-load="false" autocomplete="off" placeholder="Kode Pos"
          :conditions="[['address.*.district', 'not_empty']]" :columns="{
            sm: {
              container: 6,
            },
          }" />
      </ObjectElement>
    </template>
  </ListElement>
</template>
