<template>
  <v-combobox :items="tokens" :auto-select-first="true"
              item-title="symbol"
              :filter-keys="['raw.name','raw.symbol','raw.address']"
              :model-value="modelValue"
              :error-messages="errors"
              :loading="loading"
              :hide-selected="true"
              :label="label"
              v-bind="modelValue" @update:modelValue="updateValue"
              variant="outlined"
              autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"
              v-auto-select
  >
    <template v-slot:prepend><slot name="prepend"/></template>
    <template v-slot:item="{props,item}">
      <v-list-item v-bind="props" :prepend-avatar="item.raw.image===null?'':item.raw.image" :title="item.raw.symbol" :subtitle="item.raw.name"/>
    </template>
  </v-combobox>
</template>

<script setup>
import {useStore as useStore2} from "@/store/store";
import {computed, ref} from "vue";
import {ethers} from "ethers";
// noinspection ES6UnusedImports
import {vAutoSelect} from "@/misc.js";
import {addExtraToken} from "@/blockchain/token.js";

const s = useStore2()
const props = defineProps(['modelValue', 'label'])
const emit = defineEmits(['update:modelValue'])
const loading = ref(false)
const errors = ref([])
const tokens = computed(()=>Object.values(s.tokens))


function good() {
  errors.value = []
  loading.value = false;
}

function error(msg) {
  errors.value = [msg]
  loading.value = false;
}

function updateValue(v) {
  if( v === null ) {
    error('Type a token name, symbol, or address')
  }
  else if( typeof v !== 'string' ) {
    emit('update:modelValue', v);
    good()
  }
  else {
    try {
      const addr = ethers.getAddress(v);
      const found = s.tokens[addr]
      if(found !== undefined ) {
        good()
        emit('update:modelValue', found)
        return
      }
      errors.value = []
      loading.value = true;
      addExtraToken(addr).then((info)=>{
        if(loading.value && errors.value.length===0) {
          good()
          emit('update:modelValue', info)
        }
      }).catch((e)=>{
        // console.log(e)
        error(`${addr} is not a valid ERC20 token`)
      })
    }
    catch {
      error('Invalid token or address')
    }
  }
}
</script>


<style scoped lang="scss">
@use "src/styles/vars" as *;
</style>
