<template>
  <div class="custom-input-el calendar">
    <q-btn round size="sm" class="custom-date-btn">
      <IconCalendar />

      <q-popup-proxy
        @before-show="updateProxy"
        cover
        transition-show="scale"
        transition-hide="scale"
      >
        <q-date
          v-model="proxyDate"
          :options="optionsValidDates"
          mask="DD-MM-YYYY"
        >
          <div class="row items-center justify-end q-gutter-sm">
            <q-btn label="Cancel" color="primary" flat v-close-popup />
            <q-btn
              label="OK"
              color="primary"
              flat
              @click="save"
              v-close-popup
            />
          </div>
        </q-date>
      </q-popup-proxy>
    </q-btn>

    <div class="custom-block-content">
      <p class="custom-head-paragraph">¿Cuándo?</p>
      <q-input
        class="custom-date-input"
        label="Elige una fecha"
        placeholder="DD/MM/YYYY"
        v-model="calendar"
        mask="##/##/####"
        :error="!!errors.date"
        :error-message="errors.date"
        @blur="onBlur"
        borderless
        dense
      />
    </div>
  </div>
</template>

<script lang="ts">
import { toTypedSchema } from '@vee-validate/zod';
import { storeToRefs } from 'pinia';
import { useFormStore } from 'src/stores/forms';
import { availabilitySchema } from 'src/utils/zod/schemas/availabilitySchema';
import { useForm } from 'vee-validate';
import { defineComponent, ref } from 'vue';
import IconCalendar from '../icons/IconCalendar.vue';

export default defineComponent({
  name: 'calendar-input',
  components: { IconCalendar },
  setup() {
    const getDate = new Date();
    const currentDay = getDate.getDate().toString().padStart(2, '0');
    const currentMonth = getDate.getMonth() + 1;
    const currentYear = getDate.getFullYear();
    const fullCurrentDate = `${currentYear}/${currentMonth}/${currentDay}`;

    const formStore = useFormStore();
    const { availability } = storeToRefs(formStore);
    const proxyDate = ref(fullCurrentDate);

    const validationSchema = toTypedSchema(
      availabilitySchema.pick({ date: true })
    );
    const { errors, defineField } = useForm({
      validationSchema,
    });
    const [calendar, calendarAttrs] = defineField('date');
    const onBlur = () => {
      availability.value.date = calendar.value as string;
    };

    return {
      availability,
      proxyDate,
      calendar,
      calendarAttrs,
      errors,
      onBlur,
      updateProxy() {
        proxyDate.value = availability.value.date;
      },
      optionsValidDates(date: string) {
        return date >= fullCurrentDate /* && date <= '2019/02/15' */;
      },
      save() {
        availability.value.date = proxyDate.value;
        calendar.value = proxyDate.value;
      },
    };
  },
});
</script>
