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

<script lang="ts">
import { defineComponent, Ref, ref, useContext, computed } from '@nuxtjs/composition-api'
import {useError} from "~/composables/form/useError";

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
    }
  },
  setup (props, {emit}) {
    const { app: { i18n }, store } = useContext()
    const {error, onChange} = useError(props.field, emit, store)

    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 onChangeValue = () => {
      if (isValid.value) {
        onChange(internationalNumber.value)
      }
    }

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

    return {
      myPhone,
      error,
      onInput,
      onChangeValue,
      rules: [
        (phone: string) => (!phone || isValid.value) || i18n.t('phone_error')
      ]
    }
  }
})

</script>

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