<!--
Champs de saisie de type Text dédié à la saisie d'emails
-->

<template>
  <UiInputText
    :data="data"
    :label="$t(fieldLabel)"
    :readonly="readonly"
    :rules="rules"
    :error="error || !!fieldViolations"
    :error-messages="
        errorMessage || fieldViolations ? $t(fieldViolations) : ''
      "
    @update:model-value="onUpdate($event)"
  />
</template>

<script setup lang="ts">
import { useNuxtApp } from '#app'
import type { PropType } from 'vue'
import { useI18n } from 'vue-i18n'
import { useFieldViolation } from '~/composables/form/useFieldViolation'
import { useValidationUtils } from '~/composables/utils/useValidationUtils'

const props = defineProps({
  label: {
    type: String,
    required: false,
    default: null,
  },
  field: {
    type: String,
    required: false,
    default: null,
  },
  data: {
    type: [String, Number],
    required: false,
    default: null,
  },
  readonly: {
    type: Boolean,
    required: false,
    default: false,
  },
  required: {
    type: Boolean,
    required: false,
    default: false,
  },
  error: {
    type: Boolean,
    required: false,
  },
  errorMessage: {
    type: String,
    required: false,
    default: null,
  },
  /**
   * @see https://vuetifyjs.com/en/api/v-autocomplete/#props-variant
   */
  variant: {
    type: String as PropType<
      | 'filled'
      | 'outlined'
      | 'plain'
      | 'underlined'
      | 'solo'
      | 'solo-inverted'
      | 'solo-filled'
      | undefined
    >,
    required: false,
    default: 'outlined',
  },
})


const i18n = useI18n()

const fieldLabel = props.label ?? props.field

const { fieldViolations, updateViolationState } = useFieldViolation(props.field)

const validationUtils = useValidationUtils()

const rules = [
  (email: string) => validationUtils.validEmail(email) || i18n.t('email_error'),
]

if (props.required) {
  rules.push((email: string) => !!email || i18n.t('required'))
}

const emit = defineEmits(['update:model-value'])

const onUpdate = (event: string) => {
  updateViolationState()
  emit('update:model-value', event)
}

onBeforeUnmount(() => {
  updateViolationState()
})
</script>
