<template>
  <div class="RDateTimeInput">
    <div class="RDateTimeInput-Label">{{ label }}</div>
    <div class="RDateTimeInput-Row">
      <q-input
        v-model="innerDate"
        :mask="inputMask"
        :rules="rules"
        v-bind="$attrs"
        dense
        borderless
        hide-bottom-space
        class="RDateTimeInput-Input"
      >
        <template #append>
          <q-icon name="pgs-calendar" class="cursor-pointer">
            <q-popup-proxy
              ref="qDateProxy"
              transition-show="scale"
              transition-hide="scale"
              v-model="toggle.date"
            >
              <div class="r-date__calendar">
                <q-date
                  v-model="innerValue"
                  minimal
                  :options="dateOptions"
                  :mask="innerMask"
                  :default-year-month="defaultYearMonth"
                  @input="closePopup"
                />
              </div>
            </q-popup-proxy>
          </q-icon>
        </template>
      </q-input>
      <q-input
        v-model="innerTime"
        mask="time"
        :rules="['time']"
        type="time"
        v-bind="$attrs"
        dense
        borderless
        hide-bottom-space
        class="RDateTimeInput-Input"
      >
        <template #prepend>
          <q-icon name="pgs-time" class="cursor-pointer">
            <q-popup-proxy
              ref="qDateProxy"
              transition-show="scale"
              transition-hide="scale"
              v-model="toggle.time"
            >
              <div class="r-date__calendar">
                <q-time
                  v-model="innerValue"
                  :disable="!innerValue"
                  :options="timeOptions"
                  :mask="innerMask"
                  minimal
                  @input="closePopup"
                />
              </div>
            </q-popup-proxy>
          </q-icon>
        </template>
      </q-input>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { QPopupProxy, QDate, date as qDate, QTime } from 'quasar';
import debounce from 'lodash/debounce';

@Component
export default class RDateTimeInput extends Vue {
  @Prop({ default: 'date' }) emitFormat!: 'date' | 'timestamp' | string;
  @Prop({ default: '' }) value!: string | Date | number;
  @Prop({ default: '' }) label!: string;
  @Prop() defaultYearMonth?: string;
  @Prop({ default: null }) defaultTime?: string;
  @Prop() dateOptions: QDate['options'];
  @Prop() timeOptions: QTime['options'];
  @Prop({ default: () => [] }) rules: (
    | { (val: string): true | string }
    | string
  )[];

  prevDate: string | null = null;

  toggle = {
    date: false,
    time: false,
  };

  get innerDate(): string {
    if (!this.innerValue) return '';
    return qDate.formatDate(
      qDate.extractDate(this.innerValue, this.innerMask),
      this.dateMask
    );
  }

  set innerDate(date: string) {
    const innerDate = qDate
      .formatDate(qDate.extractDate(`${date}`, this.dateMask), this.innerMask)
      .split(' ')[0];
    this.innerValue = `${innerDate} ${this.defaultTime || this.innerTime}`;
  }

  get innerTime(): string {
    if (!this.innerValue) return '';
    const [, time] = this.innerValue.match(/(\d{2}:\d{2})/) || [];
    return time;
  }

  set innerTime(time: string) {
    if (time.length !== 5) return;
    const innerDate = qDate
      .formatDate(
        qDate.extractDate(`${this.innerDate}`, this.dateMask),
        this.innerMask
      )
      .split(' ')[0];

    this.innerValue = `${innerDate} ${time}`;
  }

  innerValue = '';

  get inputMask(): string {
    return '##.##.####';
  }

  get dateMask(): string {
    return 'DD.MM.YYYY';
  }

  get innerMask(): string {
    return 'YYYY-MM-DD HH:mm';
  }

  getEmitValue(val: string): Date | number | string {
    switch (this.emitFormat) {
      case 'date':
        return qDate.extractDate(val, this.innerMask);
      case 'timestamp':
        return +qDate.extractDate(val, this.innerMask);
      case this.innerMask:
        return val;
      default:
        return qDate.formatDate(
          qDate.extractDate(val, this.innerMask),
          this.emitFormat
        );
    }
  }

  getInnerValue(val: string | Date | number): string {
    switch (this.emitFormat) {
      case 'date':
      case 'timestamp':
        return qDate.formatDate(val, this.innerMask);
      case this.innerMask:
        return String(val);
      default:
        return qDate.formatDate(
          qDate.extractDate(String(val), this.emitFormat),
          this.innerMask
        );
    }
  }

  @Watch('value', { immediate: true })
  private setInnerValue(val?: string | Date | number) {
    if (!val) return;
    this.innerValue = this.getInnerValue(val);
  }

  reset(): void {
    this.innerValue = this.getInnerValue(this.value);
  }

  clearButtonHidden = false;

  // hideClearButton(e: Event): boolean | undefined {
  //   try {
  //     console.log((e.target as any).firstChild);

  //     // fixme избавиться от try catch
  //     const { arrowLeft, arrowRight } = this.$q.iconSet.datetime;
  //     const arrow = (e.target as any).firstChild.data.trim();

  //     if (arrow !== arrowLeft && arrow !== arrowRight) return false;
  //   } catch (e) {
  //     return false;
  //   }

  //   this.clearButtonHidden = true;
  //   this.showClearButton();
  // }

  showClearButton!: () => void;

  closePopup(): void {
    (this.$refs.qDateProxy as QPopupProxy).hide();
  }

  @Watch('innerValue')
  private innerValueChanged(val: string) {
    if (val) {
      const currentValue: string[] = val.split(' ');
      const innerDate = currentValue[0];
      if (this.defaultTime && this.prevDate !== innerDate) {
        currentValue[1] = this.defaultTime;
        this.prevDate = innerDate;
      }
      this.$emit('input', currentValue.join(' ') ? this.getEmitValue(currentValue.join(' ')) : '');
    } else {
      this.prevDate = null;
      this.$emit('input', null);
    }
    this.toggle.date = false;
    this.toggle.time = false;
  }

  created(): void {
    this.showClearButton = debounce(
      () => (this.clearButtonHidden = false),
      200
    );
  }

  dateRule() {
    return true; // todo
  }
}
</script>

<style lang="scss">
.RDateTimeInput {
  display: flex;
  flex-direction: column;

  &-Row {
    display: flex;
    flex-flow: row nowrap;
    gap: 8px;
  }
  &-Label {
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 600;
    font-size: 12px;
    line-height: 16px;
    color: rgba(2, 12, 18, 0.58);
    margin-bottom: 4px;
  }
  &-Input {
    background: #e5edf5;
    border-radius: 4px 4px 0 0;
    background-blend-mode: multiply;
    border: none;
    border-bottom: 1px solid rgba(1, 72, 116, 0.18);
    padding: 8px;
    box-sizing: border-box;
    transition: 0.1s;
    height: 32px;
    &:focus {
      transition: 0.1s;
      outline: none;
      background-color: white;
      box-shadow: inset 0 0 2px rgba(15, 104, 160, 0.87);
      border-color: #1487cf;
    }
  }

  input[type='time']::-webkit-calendar-picker-indicator {
    background: none;
  }
}
// .r-date
//   &__input
//     width: 10.5em

//     .q-field__control
//       padding: 0 12px !important

//   &__calendar
//     position: relative

//   &__clear
//     opacity: 1
//     position: absolute
//     right: 24px
//     bottom: 20px
//     padding-right: 8px
//     padding-left: 8px
//     box-shadow: none
//     transition: opacity .2s

//     &--hidden
//       opacity: 0
</style>
