<template>
  <v-menu
    v-model="dateOpen"
    :close-on-content-click="false"
    :nudge-right="40"
    transition="scale-transition"
    offset-y
    min-width="auto"
  >
    <template v-slot:activator="{ on, attrs }">
      <v-text-field
        v-model="dateFormatted"
        :label="$t(label_field)"
        prepend-icon="mdi-calendar"
        :disabled="readOnly"
        v-bind="attrs"
        v-on="on"
      ></v-text-field>
    </template>
    <v-date-picker
      v-model="dateParsed"
      @input="dateOpen = false"
      locale="fr"
      color="ot_green lighten-1"
    ></v-date-picker>
  </v-menu>
</template>


<script lang="ts">
  import {defineComponent, watch, ref, useContext, onUnmounted} from '@nuxtjs/composition-api'

  export default defineComponent({
    props: {
      field: {
        type: String,
        required: false
      },
      label: {
        type: String,
        required: false
      },
      data: {
        type: String,
        required: false
      },
      readOnly: {
        type: Boolean,
        required: false
      },
    },
    setup(props, {emit}){
      const {data, field} = props
      const {$moment} = useContext()

      const dateFormatted = ref($moment(data).format('DD/MM/YYYY'))
      const dateParsed = ref($moment(data).format('YYYY-MM-DD'))

      const unwatch = watch(dateParsed, (newValue) => {
        dateFormatted.value = $moment(newValue).format('DD/MM/YYYY')
        emit('update', newValue, field)
      })

      onUnmounted(()=>{
        unwatch()
      })

      return {
        label_field : props.label ?? props.field,
        dateParsed,
        dateFormatted,
        dateOpen: false
      }
    }
  })
</script>

<style scoped>
</style>
