<template>
  <div>
    <div
      class="calendar__tooltip"
      v-if="showTooltip &amp;&amp; this.options.hoveringTooltip"
      v-html="tooltipMessageDisplay"
    ></div>
    <div
      class="calendar__month-day"
      @click.prevent.stop="dayClicked(date)"
      @keyup.enter.prevent.stop="dayClicked(date)"
      v-text="dayNumber"
      :class="dayClass"
      :style="isToday ? currentDateStyle : ''"
      :tabindex="tabIndex"
      ref="day"
    ></div>
  </div>
</template>

<script>
import fecha from "fecha";
import Helpers from "../../helpers.js";
export default {
  name: "Day",
  props: {
    isOpen: {
      type: Boolean,
      required: true
    },
    sortedDisabledDates: {
      type: Array
    },
    options: {
      type: Object
    },
    checkIn: {
      type: Date
    },
    checkOut: {
      type: Date
    },
    hoveringDate: {
      type: Date
    },
    mounseOverFunction: {
      type: Function
    },
    belongsToThisMonth: {
      type: Boolean
    },
    activeMonthIndex: {
      type: Number
    },
    date: {
      type: Date
    },
    dayNumber: {
      type: String
    },
    nextDisabledDate: {
      type: [Date, Number, String]
    },
    hoveringTooltip: {
      default: true,
      type: Boolean
    },
    tooltipMessage: {
      default: null,
      type: String
    },
    currentDateStyle: {
      type: [Object, null, String],
      required: true
    }
  },
  data() {
    return {
      isHighlighted: false,
      allowedCheckoutDays: [],
      currentDate: new Date()
    };
  },
  computed: {
    tabIndex() {
      if (!this.isOpen || !this.belongsToThisMonth || !this.isClickable()) {
        return -1;
      }
      return 0;
    },
    nightsCount() {
      return Helpers.countDays(this.checkIn, this.hoveringDate);
    },
    tooltipMessageDisplay() {
      return this.tooltipMessage
        ? this.tooltipMessage
        : `${this.nightsCount + 1} ${
            this.nightsCount + 1 !== 1
              ? this.options.i18n["nights"]
              : this.options.i18n["night"]
          }`;
    },
    showTooltip() {
      return (
        this.date === this.hoveringDate &&
        this.checkIn !== null &&
        this.checkOut == null
      );
    },

    isToday() {
      return this.compareDay(this.currentDate, this.date) === 0;
    },

    // eslint-disable-next-line vue/return-in-computed-property
    dayClass() {
      if (this.belongsToThisMonth) {
        // If the calendar has a minimum number of nights

        // If the calendar has allowed ranges
        if (this.options.allowedRanges.length !== 0) {
          if (this.checkIn !== null && this.checkOut == null) {
            // If the day is one of the allowed check out days and is not highlighted
            if (
              this.allowedCheckoutDays.some(
                i => this.compareDay(i, this.date) === 0 && !this.isHighlighted
              )
            ) {
              return "calendar__month-day--allowed-checkout";
            }
            // If the day is one of the allowed check out days and is highlighted
            if (
              this.allowedCheckoutDays.some(
                i => this.compareDay(i, this.date) === 0 && this.isHighlighted
              )
            ) {
              return "calendar__month-day--selected calendar__month-day--allowed-checkout";
            }
            // If the day is not one of the allowed Checkout Days and is highlighted
            if (
              !this.allowedCheckoutDays.some(
                i => this.compareDay(i, this.date) === 0
              ) &&
              this.isHighlighted
            ) {
              return "calendar__month-day--out-of-range calendar__month-day--selected";
            } else {
              return "calendar__month-day--out-of-range";
            }
          }
        }
        // Highlight the selected dates and prevent the user from selecting
        // the same date for checkout and checkin
        if (
          this.checkIn !== null &&
          fecha.format(this.checkIn, "YYYYMMDD") ===
            fecha.format(this.date, "YYYYMMDD")
        ) {
          if (this.options.minNights === 0) {
            return "calendar__month-day--first-day-selected";
          } else {
            return "calendar__month-day--disabled calendar__month-day--first-day-selected";
          }
        }
        if (this.checkOut !== null) {
          if (
            fecha.format(this.checkOut, "YYYYMMDD") ===
            fecha.format(this.date, "YYYYMMDD")
          ) {
            return "calendar__month-day--disabled calendar__month-day--last-day-selected";
          }
        }
        // Only highlight dates that are not disabled
        if (this.isHighlighted) {
          return "calendar__month-day--selected";
        }
        // if (!this.isDisabled) {
        //   return "calendar__month-day--disabled";
        // }
      } else if (!this.belongsToThisMonth) {
        return "calendar__month-day--hidden";
      }
      // return "calendar__month-day--valid";
    }
  },
  watch: {
    hoveringDate() {
      this.fetchHighlight();
    },
    activeMonthIndex() {
      this.checkIfHighlighted();
      if (this.checkIn !== null && this.checkOut !== null) {
        Helpers.isDateLessOrEquals(this.checkIn, this.date) &&
        Helpers.isDateLessOrEquals(this.date, this.checkOut)
          ? (this.isHighlighted = true)
          : (this.isHighlighted = false);
      } else if (this.checkIn !== null && this.checkOut == null) {
        this.disableNextDays();
      }
    },
    nextDisabledDate() {
      this.disableNextDays();
    },
    checkIn(date) {
      this.createAllowedCheckoutDays(date);
      this.fetchHighlight();
    }
  },
  beforeMount() {
    this.checkIfHighlighted();
  },
  methods: {
    isClickable() {
      if (this.$refs && this.$refs.day) {
        return getComputedStyle(this.$refs.day).pointerEvents !== "none";
      } else {
        return true;
      }
    },

    compareDay(day1, day2) {
      const date1 = fecha.format(new Date(day1), "YYYYMMDD");
      const date2 = fecha.format(new Date(day2), "YYYYMMDD");

      if (date1 > date2) {
        return 1;
      } else if (date1 === date2) {
        return 0;
      } else if (date1 < date2) {
        return -1;
      }
    },

    dayClicked(date) {
      if (this.options.allowedRanges.length !== 0) {
        this.createAllowedCheckoutDays(date);
      }

      let nextDisabledDate =
        (this.options.maxNights
          ? this.addDays(this.date, this.options.maxNights)
          : null) ||
        this.allowedCheckoutDays[this.allowedCheckoutDays.length - 1] ||
        Helpers.getNextDate(this.sortedDisabledDates, this.date) ||
        Helpers.nextDateByDayOfWeekArray(
          this.options.disabledDaysOfWeek,
          this.date
        ) ||
        Infinity;

      if (this.options.enableCheckout) {
        nextDisabledDate = Infinity;
      }

      this.$emit("day-clicked", { date, nextDisabledDate });
    },

    compareEndDay() {
      if (this.options.endDate !== Infinity) {
        return this.compareDay(this.date, this.options.endDate) === 1;
      }
    },

    checkIfHighlighted() {
      if (this.checkIn !== null && this.checkOut !== null) {
        Helpers.isDateLessOrEquals(this.checkIn, this.date) &&
        Helpers.isDateLessOrEquals(this.date, this.checkOut)
          ? (this.isHighlighted = true)
          : (this.isHighlighted = false);
      }
    },

    createAllowedCheckoutDays(date) {
      this.allowedCheckoutDays = [];
      this.options.allowedRanges.forEach(i =>
        this.allowedCheckoutDays.push(this.addDays(date, i))
      );
      this.allowedCheckoutDays.sort((a, b) => a - b);
    },

    disableNextDays() {
      if (
        !Helpers.isDateLessOrEquals(this.date, this.nextDisabledDate) &&
        this.nextDisabledDate !== Infinity
      ) {
        // console.log("primer if?");
      } else if (
        Helpers.isDateLessOrEquals(
          this.date,
          new Date().setDate(this.options.startDate.getDate() - 1)
        )
      ) {
        // console.log("segundo if?");
      }
      if (
        this.compareDay(this.date, this.checkIn) === 0 &&
        this.options.minNights === 0
      ) {
        // console.log("tercer if?");
      }
      if (
        Helpers.isDateLessOrEquals(this.checkIn, this.date) &&
        this.options.enableCheckout
      ) {
        // console.log("cuarto if?");
      }
    },

    fetchHighlight() {
      if (this.checkIn !== null && this.checkOut == null) {
        if (!Helpers.isDateLessOrEquals(this.checkIn, this.date)) {
          this.isHighlighted = false;
        } else {
          Helpers.isDateLessOrEquals(this.date, this.hoveringDate)
            ? (this.isHighlighted = true)
            : (this.isHighlighted = false);
        }
      }
      if (this.checkIn !== null && this.checkOut == null) {
        // console.log("Importante por algun motivo");
      }
    }
  }
};
</script>
