<!--
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"
      v-model="myPhone"
      :readonly="readonly"
      clearable
      valid-characters-only
      validate-on-blur
      :rules="rules"
      @input="onInput"
      @change="onChange"
    />
  </client-only>
</template>

<script lang="ts">
import { defineComponent, Ref, ref, useContext, computed } 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 (props, {emit}) {
    const { app: { i18n } } = useContext()

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

    const onInput = (_: any, { number, valid, countryChoice }: { number: any, valid: boolean, countryChoice: any }) => {
      isValid.value = valid
      nationalNumber.value = number.national
      internationalNumber.value = number.international
      onInit.value = false
    }

    const onChange = () => {
      if (isValid.value) {
        emit('update', internationalNumber.value, props.field)
      }
    }

    const myPhone = computed(
      {
        get:()=>{
          return onInit.value ? props.data : nationalNumber.value
        },
        set:(value)=>{
          return props.data
        }
      }
    )

    return {
      myPhone,
      onInput,
      onChange,
      rules: [
        () => isValid.value || i18n.t('phone_error')
      ]
    }
  }
})

</script>

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