<!--
An input for numeric values
-->
<!-- eslint-disable vue/valid-v-bind -->

<template>
  <v-text-field
    ref="input"
    :model-value.number="modelValue"
    :label="label || field ? $t(label ?? field) : undefined"
    :rules="rules"
    type="number"
    :variant="variant"
    density="compact"
    :error="error || !!fieldViolations"
    :error-messages="
      errorMessage || (fieldViolations ? $t(fieldViolations) : '')
    "
    @update:model-value="onModelUpdate($event)"
    @change="onChange($event)"
  />
</template>

<script setup lang="ts">
import type { PropType, Ref } from 'vue'
import {useFieldViolation} from "~/composables/form/useFieldViolation";

type ValidationRule = (value: string | number | null) => boolean | string

const props = defineProps({
  modelValue: {
    type: Number,
    required: true,
  },
  /**
   * Nom de la propriété d'une entité lorsque l'input concerne cette propriété
   * - Utilisé par la validation
   * - Laisser null si le champ ne s'applique pas à une entité
   */
  field: {
    type: String,
    required: false,
    default: null,
  },
  /**
   * Label du champ
   * Si non défini, c'est le nom de propriété qui est utilisé
   */
  label: {
    type: String,
    required: false,
    default: null,
  },
  default: {
    type: Number,
    required: false,
    default: 0,
  },
  min: {
    type: Number,
    required: false,
    default: null,
  },
  max: {
    type: Number,
    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',
  },
  /**
   * Règles de validation
   * @see https://vuetify.cn/en/components/forms/#validation-with-submit-clear
   */
  rules: {
    type: Array as PropType<ValidationRule[]>,
    required: false,
    default: () => [],
  },
  /**
   * Le champ est-il actuellement en état d'erreur
   */
  error: {
    type: Boolean,
    required: false,
    default: false,
  },
  /**
   * Si le champ est en état d'erreur, quel est le message d'erreur?
   */
  errorMessage: {
    type: String,
    required: false,
    default: null,
  },
})

/**
 * Reference to the v-text-field
 */
// eslint-disable-next-line
const input: Ref<any> = ref(null)

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

/**
 * Cast the value to a number, or fallback on default value
 * @param val
 */
const cast = (val: number | string): number => {
  val = Number(val)
  if (isNaN(val)) {
    return props.default
  }

  return val
}

/**
 * Ensure the value is between min and max values
 * @param val
 */
const keepInRange = (val: number) => {
  if (props.min !== null && props.max !== null && props.min >= props.max) {
    console.warn('Number input: minimum value is greater than maximum value')
  }
  if (props.min !== null && val < props.min) {
    val = props.min
  }
  if (props.max !== null && val > props.max) {
    val = props.max
  }
  return val
}

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

const onModelUpdate = (event: string) => {
  emit('update:modelValue', keepInRange(cast(event)))
}

const onChange = (event: Event | undefined) => {
  updateViolationState()
  emit('change', event)
}

/**
 * Setup min and max values at the input level
 */
onMounted(() => {
  const inputElement = input.value!.$el.querySelector('input')
  if (props.min !== null) {
    inputElement.min = props.min
  }
  if (props.max !== null) {
    inputElement.max = props.max
  }
})

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