<template>
  <v-row>
    <v-col cols="12" md="6">
      <v-text-field
        :model-value="
          dateModel
            ? _useDate.format(dateModel, 'fullDateWithWeekday')
            : undefined
        "
        :label="$t('choose_day')"
        prepend-icon="fas fa-calendar"
        :rules="rules"
        :variant="variant"
        :error="error || !!fieldViolations"
        :error-messages="
          errorMessage || (fieldViolations ? $t(fieldViolations) : '')
        "
        readonly
      >
        <v-menu
          v-model="showMenuDate"
          :close-on-content-click="false"
          activator="parent"
          min-width="0"
        >
          <v-date-picker
            :model-value="dateModel"
            @update:model-value="onUpdateDate($event)"
          />
        </v-menu>
      </v-text-field>
    </v-col>

    <v-col cols="12" md="6">
      <v-text-field
        :model-value="time"
        :variant="variant"
        :label="$t('choose_hour')"
        prepend-icon="fas fa-clock"
        :rules="rules"
        :error="error || !!fieldViolations"
        :error-messages="
          errorMessage || (fieldViolations ? $t(fieldViolations) : '')
        "
        readonly
      >
        <v-menu
          v-model="showMenuTime"
          :close-on-content-click="false"
          activator="parent"
          min-width="0"
        >
          <v-time-picker
            :model-value="time"
            format="24hr"
            scrollable
            @update:model-value="onUpdateTime($event)"
          />
        </v-menu>
      </v-text-field>
    </v-col>
  </v-row>
</template>

<script setup lang="ts">
import { ref, computed, onBeforeUnmount, type PropType } from 'vue'
import { useFieldViolation } from '~/composables/form/useFieldViolation'
import { useDate } from 'vuetify'
import DateUtils from '~/services/utils/dateUtils'

const props = defineProps({
  /**
   * v-model
   */
  modelValue: {
    type: String as PropType<Date | string | null>,
    required: false,
    default: null,
  },

  /**
   * 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,
  },
  /**
   * Définit si le champ est en lecture seule
   */
  readonly: {
    type: Boolean,
    required: false,
  },
  /**
   * Règles de validation
   * @see https://vuetify.cn/en/components/forms/#validation-with-submit-clear
   */
  rules: {
    type: Array as PropType<Array<(value: unknown) => boolean | string>>,
    required: false,
    default: () => [],
  },
  /**
   * Le champ est-il actuellement en état d'erreur
   */
  error: {
    type: Boolean,
    required: false,
  },
  /**
   * Si le champ est en état d'erreur, quel est le message d'erreur?
   */
  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 showMenuTime = ref(false)
const showMenuDate = ref(false)
const _useDate = useDate()
const { fieldViolations, updateViolationState } = useFieldViolation(props.field)

const dateModel = computed(() =>
  props.modelValue ? new Date(props.modelValue) : undefined,
)
const time = computed(() =>
  props.modelValue
    ? _useDate.format(new Date(props.modelValue), 'fullTime24h')
    : undefined,
)
const emit = defineEmits(['update:model-value'])

const onUpdateDate = (event: Date) => {
  updateViolationState()
  const date = DateUtils.combineDateAndTime(event, time.value)
  emit('update:model-value', date.toISOString().replace('.000Z', '+00:00'))
}

const onUpdateTime = (event: string) => {
  updateViolationState()
  const date = DateUtils.combineDateAndTime(dateModel.value, event)
  emit('update:model-value', date.toISOString().replace('.000Z', '+00:00'))
}

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

<style scoped lang="scss"></style>
