<template>
  <main>
    <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="datesFormatted"
          autocomplete="off"
          :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="datesParsed"
        @input="dateOpen = range && datesParsed.length < 2"
        locale="fr"
        :range="range"
        color="ot_green lighten-1"
      ></v-date-picker>
    </v-menu>
  </main>
</template>


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

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

      const datesFormatted = ref()
      const datesParsed = range ? ref(Array<string>()) : ref()

      if(range){
        for(const date of data as Array<string>){
          datesParsed.value.push($moment(date).format('YYYY-MM-DD'))
        }
      }else{
        datesParsed.value = $moment(data as string).format('YYYY-MM-DD')
      }
      datesFormatted.value = datesFormatted.value = useDate.handleFormattedDate(data)

      const unwatch = watch(datesParsed, (newValue) => {
        if(range && newValue.length < 2) return
        datesFormatted.value = useDate.handleFormattedDate(newValue)
        emit('update', newValue, field)
      })

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

      return {
        label_field : props.label ?? props.field,
        datesParsed,
        datesFormatted,
        dateOpen: ref(false)
      }
    }
  })
</script>

<style scoped>
</style>
