<template>
  <div class="flex no-wrap items-center q-mt-lg">
    <div class="date-picker-wrap">
      <preview-days-picker
        @input="showPreview(true)"
        v-model="modelDate"
        v-if="!isShowPreview"
      />
      <div
        v-else
        @click="isShowDatePicker = true"
        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
  height: 72px
</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 })
  isShowPreview!: 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

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

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

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

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

  @Emit()
  showPreview(value: boolean) {
    return value
  }

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

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