<template>
  <v-text-field
    :model-value="modelValue"
    :rules="[validateRequired, validatePhone]"
    :label="label"
    :required="required"
    type="tel"
    @update:model-value="updateValue"
  />
</template>

<script setup lang="ts">
import { isValidPhoneNumber } from 'libphonenumber-js'

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  label: {
    type: String,
    default: 'Téléphone',
  },
  required: {
    type: Boolean,
    default: false,
  },
  countryCode: {
    type: String,
    default: 'FR',
  },
})

const emit = defineEmits(['update:modelValue'])

const updateValue = (value: string) => {
  emit('update:modelValue', value)
}

// Validation rules
const validateRequired = (value: string) =>
  !props.required || !!value || 'Ce champ est obligatoire'

const validatePhone = (phone: string) => {
  if (!phone) return true
  try {
    // Use the provided country code or default to FR
    return (
      isValidPhoneNumber(phone, props.countryCode) ||
      'Numéro de téléphone invalide'
    )
  } catch (error) {
    return 'Numéro de téléphone invalide'
  }
}
</script>
