import VanillaCalendar from 'vanilla-calendar-pro';
import 'vanilla-calendar-pro/build/vanilla-calendar.min.css';

export async function initCalendar() {
  async function fetchActiveDates() {
    const apiUrl = `${
      import.meta.env.VITE_API_URL || ''
    }/wp-json/agroexpert/v1/posts-by-date/`;

    try {
      const response = await fetch(apiUrl);

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      return data;
    } catch (error) {
      console.error('Could not fetch active dates:', error);
      throw error;
    }
  }

  function getFormattedDate() {
    const months = [
      'января',
      'февраля',
      'марта',
      'апреля',
      'мая',
      'июня',
      'июля',
      'августа',
      'сентября',
      'октября',
      'ноября',
      'декабря',
    ];

    const currentDate = new Date();
    const day = currentDate.getDate();
    const monthIndex = currentDate.getMonth();
    const year = currentDate.getFullYear();

    const formattedDate = `${day} ${months[monthIndex]} ${year}`;

    return formattedDate;
  }

  const activeDates = [...(await fetchActiveDates())].map(date => {
    const [year, month, day] = date.split('-');
    const link = `${window.location.protocol}//${window.location.host}/${year}/${month}/${day}/`;

    return {
      date,
      link,
    };
  });

  const options = {
    settings: {
      lang: 'ru',
      selected: {
        dates: activeDates.map(d => d.date),
      },
      visibility: {
        theme: 'light',
      },
    },
    locale: {
      months: [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
        'August',
        'September',
        'October',
        'November',
        'December',
      ],
      weekday: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    },
  };

  const eventCalendarHeader = document.querySelector('.event-calendar__header');
  const eventCalendarWrapper = document.querySelector(
    '.event-calendar__wrapper'
  );
  const eventCalendarToday = document.querySelector('#event-calendar__today');

  if (eventCalendarToday) {
    eventCalendarToday.innerHTML = getFormattedDate();
  }

  if (eventCalendarHeader && eventCalendarWrapper) {
    eventCalendarHeader.addEventListener('click', () => {
      eventCalendarWrapper.classList.toggle('is-active');
      eventCalendarHeader.classList.toggle('is-active');
    });
  }

  if (document.querySelector('#calendar_event')) {
    const calendar = new VanillaCalendar('#calendar_event', options);
    calendar.init();
  }

  if (document.querySelector('#calendar')) {
    const calendar = new VanillaCalendar('#calendar', options);
    calendar.init();
  }

  document.addEventListener('click', function (event) {
    const target = event.target.closest('[data-calendar-day]');

    if (target) {
      const clickedDate = target.getAttribute('data-calendar-day');

      const dateObject = activeDates.find(
        dateObj => dateObj.date === clickedDate
      );

      if (dateObject) {
        window.location.href = dateObject.link;
      }
    }
  });
}
