<!--
Champs de saisie d'un numéro de téléphone

@see https://github.com/yogakurniawan/vue-tel-input-vuetify
-->

<template>
  <client-only>
    <vue-tel-input-vuetify
      :field="field"
      :label="label"
      :value="data"
      :readonly="readonly"
      clearable
      valid-characters-only
      validate-on-blur
      :rules="rules"
      :active-country="{iso2: 'FR'}"
      @input="onInput"
      @change="onChange"
    />
  </client-only>
</template>

<script lang="ts">
import { defineComponent, Ref, ref, useContext } from '@nuxtjs/composition-api'

export default defineComponent({
  props: {
    label: {
      type: String,
      required: false,
      default: ''
    },
    field: {
      type: String,
      required: false,
      default: null
    },
    data: {
      type: [String, Number],
      required: false,
      default: null
    },
    readonly: {
      type: Boolean,
      required: false
    },
    error: {
      type: Boolean,
      required: false
    },
    errorMessage: {
      type: String,
      required: false,
      default: null
    }
  },
  setup () {
    const { app: { i18n } } = useContext()

    const nationalNumber: Ref<string | number> = ref('')
    const internationalNumber: Ref<string | number> = ref('')
    const isValid: Ref<boolean> = ref(false)
    const country: Ref<string> = ref('')

    return {
      nationalNumber,
      internationalNumber,
      isValid,
      country,
      rules: [
        () => isValid.value || i18n.t('phone_error')
      ]
    }
  },
  methods: {
    onInput (_: any, { number, valid, country }: { number: any, valid: boolean, country: any }) {
      this.isValid = valid
      this.nationalNumber = number.national
      this.internationalNumber = number.international
      this.country = country && country.name
      // console.log(this.field, this.isValid, this.nationalNumber, this.internationalNumber, this.country)
    },
    onChange () {
      if (this.isValid) {
        this.$emit('update', this.internationalNumber, this.field)
      }
    }
  }
})

</script>

<style>
input:read-only{
  color: #666 !important;
}
</style>
