<template>
  <div class="flex no-wrap items-center q-mt-lg">
    <div class="date-picker-wrap">
      <preview-days-picker
        @input="isValueSelected = true"
        v-model="modelDate"
        v-if="!isValueSelected"
      />
      <div v-else class="text-center full-width">
        {{ label }}
      </div>
      <q-space />
      <ui-btn-icon
        icon="la la-calendar-alt"
        color="secondary"
        class="self-center q-ml-sm"
        size="lg"
        dense
        flat
      >
        <q-popup-proxy v-model="isShowDatePicker">
          <ui-date-picker
            @input="updateModelFromDatePicker"
            v-model="dateAsString"
          />
        </q-popup-proxy>
      </ui-btn-icon>
    </div>
    <time-picker :hours.sync="hours" :minutes.sync="minutes" />
  </div>
</template>

<style scoped lang="sass">
.date-picker-wrap
  display: flex
  align-items: center
  background-color: $background
  border-radius: 8px
  padding: 8px
  width: 228px
</style>

<script lang="ts">
import { Component, Emit, Prop, Vue, Watch } from 'vue-property-decorator'
import { date, QPopupProxy, QSpace } from 'quasar'
import UiDatePicker from '@/lib-components/form/UiDatePicker.vue'
import PreviewDaysPicker from '@/widgets/tasks/components/form/date-picker/PreviewDaysPicker.vue'
import UiBtnIcon from '@/lib-components/buttons/UiBtnIcon.vue'
import DateHelper from '@/helpers/DateHelper'
import TimePicker from '@/widgets/tasks/components/form/date-picker/TimePicker.vue'

@Component({
  components: {
    TimePicker,
    UiBtnIcon,
    PreviewDaysPicker,
    UiDatePicker,
    QSpace,
    QPopupProxy,
  },
  inheritAttrs: false,
})
export default class DatePicker extends Vue {
  @Prop(Date)
  value!: Date

  @Prop({ type: Boolean, default: false })
  hidePreviewPicker!: boolean

  dateAsString = date.formatDate(this.value, 'YYYY/MM/DD')
  modelDate: Date = date.extractDate(this.dateAsString, 'YYYY/MM/DD')

  hours = this.value.getHours()
  minutes = this.value.getMinutes()
  isShowDatePicker = false
  isValueSelected = this.hidePreviewPicker

  get label(): string {
    return DateHelper.getFullDate(this.modelDate.getTime())
  }

  updateModelFromDatePicker(dateAsString: string) {
    if (dateAsString) {
      this.modelDate = date.extractDate(dateAsString, 'YYYY/MM/DD')

      this.isValueSelected = true
    }

    this.$nextTick(() => (this.isShowDatePicker = false))
  }

  @Emit()
  input(date: Date) {
    return date
  }

  @Watch('modelDate')
  @Watch('hours')
  @Watch('minutes')
  emitInput() {
    const targetDate: Date = date.addToDate(this.modelDate, {
      minutes: this.minutes,
      hours: this.hours,
    })

    this.input(targetDate)
  }
}
</script>
