var Wick = window.Wick || {};

Wick.Flatpickr = {
  el: {
    $crossIcon: $("#crossIcon"),
    $calendarIcon: $("#calendarIcon"),
    flatpickrDisabled: '.flatpickr-disabled',
    datePickerField: '.flatpickr-datepicker__field',
  },
  generateInitialDisabledMonths(year, startMonth) {
    const today = new Date();
    const currentYear = today.getFullYear();
    const currentMonth = today.getMonth();

    if (year === currentYear) {
      return Array.from({ length: 12 - currentMonth - 1 }, (_, i) =>
        new Date(year, currentMonth + 1 + i, 1)
      );
    }

    return [];
  },
  handleYearChange(instance, minYear, currentYear, currentMonth) {
    const selectedYear = instance.currentYear;

    if (selectedYear > currentYear) {
      instance.changeYear(currentYear);
    } else if (selectedYear < minYear) {
      instance.changeYear(minYear);
    }

    Wick.Flatpickr.updateDisabledMonths(instance, selectedYear, currentMonth, currentYear);
  },
  updateDisabledMonths(instance, year, month) {
    const disabledMonths = Wick.Flatpickr.generateInitialDisabledMonths(year, month);
    instance.set("disable", disabledMonths);
  },
  bindClearIcon(instance, $field) {
    if ($field.val().trim() !== "") {
      Wick.Flatpickr.el.$crossIcon.removeClass("d-none").addClass("d-flex");
    } else {
      Wick.Flatpickr.el.$crossIcon.removeClass("d-flex").addClass("d-none");
    }

    Wick.Flatpickr.el.$crossIcon.on("click", function () {
      instance.clear();
      instance.setDate(null);
      $field.val("");
      Wick.Flatpickr.el.$crossIcon.hide();
      instance.open();
      instance.close();
    });

    $field.on("input", function () {
      if ($field.val().trim() === "") {
        Wick.Flatpickr.el.$crossIcon.removeClass("d-flex").addClass("d-none");
      } else {
        Wick.Flatpickr.el.$crossIcon.removeClass("d-none").addClass("d-flex");
      }
    });
  },
  bindCalendarIcon(instance) {
    Wick.Flatpickr.el.$calendarIcon.on("click", function () {
      instance.open();
    });
  },
  formatDateToYYYYMM(date) {
    const newDate = new Date(date);
    const year = newDate.getFullYear();
    const month = String(newDate.getMonth() + 1).padStart(2, "0");
    return `${year}-${month}`;
  },
  getFlatpickrConfig(config) {
    const today = new Date();
    const chooseDate = config.chooseDate
      ? new Date(config.chooseDate)
      : null;
    const currentYear = config.currentYear || today.getFullYear();
    const currentMonth = chooseDate ? chooseDate.getMonth() : today.getMonth();
    const minYear = config.minYear || currentYear - 15;

    const minDate = new Date(minYear, 0, 1);
    const maxDate = new Date(`${currentYear}-12-31`);

    const initialDisabledMonths = Wick.Flatpickr.generateInitialDisabledMonths(
      today.getFullYear(),
      currentMonth
    );

    return {
      dateFormat: config.dateFormat || "F Y",
      enableTime: false,
      static: config.static || true,
      defaultDate: chooseDate || null,
      placeholder: "Select year and month",
      minDate,
      maxDate,
      disable: initialDisabledMonths,
      plugins: [
        new monthSelectPlugin({
          shorthand: false,
          dateFormat: config.dateFormat || "F Y",
          theme: "light",
        }),
      ],
      onYearChange: (selectedDates, dateStr, instance) => {
        Wick.Flatpickr.handleYearChange(
          instance,
          minYear,
          currentYear,
          currentMonth
        );
      },
      onMonthChange: (selectedDates, dateStr, instance) => {
        Wick.Flatpickr.updateDisabledMonths(
          instance,
          currentYear,
          currentMonth
        );
      },
      onReady: (selectedDates, dateStr, instance) => {
        Wick.Flatpickr.updateDisabledMonths(
          instance,
          currentYear,
          currentMonth
        );
      },
      onOpen: (selectedDates, dateStr, instance) => {
        $(Wick.Flatpickr.el.datePickerField).addClass('active');
      },
      onClose: (selectedDates, dateStr, instance) => {
        $(Wick.Flatpickr.el.datePickerField).removeClass("active");
        $(Wick.Flatpickr.el.flatpickrDisabled).removeClass("flatpickr-disabled");

        if (selectedDates.length > 0) {
          const selectedDate = selectedDates[0];
          const selectedYear = selectedDate.getFullYear();
          const selectedMonth = selectedDate.getMonth();
          instance.currentYear = selectedYear;
          instance.currentMonth = selectedMonth;

          Wick.Flatpickr.updateDisabledMonths(instance, selectedYear, selectedMonth);
        }
      },
      onChange: (selectedDates, dateStr) => {
        const { onChangeCallback } = config;
        if (typeof onChangeCallback === "function") {
          const formattedDate = Wick.Flatpickr.formatDateToYYYYMM(selectedDates[0]);
          onChangeCallback(formattedDate);
        }
      },
    };
  },
  init(config) {
    const $field = $(config.id);

    if (!$field.length) {
      return;
    }

    const flatpickrConfig = Wick.Flatpickr.getFlatpickrConfig(config);
    const flatpickrInstance = flatpickr(config.id, flatpickrConfig);

    Wick.Flatpickr.bindClearIcon(flatpickrInstance, $field);
    Wick.Flatpickr.bindCalendarIcon(flatpickrInstance);
  },
};
