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

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

// TODO: tester compatibilité avec Vue 3
-->

<template>
  <client-only>
    <vue-tel-input-vuetify
      :error="error || !!violation"
      :error-messages="errorMessage || violation ? $t(violation) : ''"
      :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 setup lang="ts">

import {useNuxtApp} from "#app";
import {useFieldViolation} from "~/composables/form/useFieldViolation";
import {Ref} from "@vue/reactivity";

const props = defineProps({
  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
  }
})

const { emit, i18n } = useNuxtApp()

const { violation, onChange } = useFieldViolation(props.field, emit)

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
    }
  }
)

const rules = [
  (phone: string) => (!phone || isValid.value) || i18n.t('phone_error')
]
</script>

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