/* eslint-disable */
import { onPageLoadComplete } from '@nimius/event-utility';
import flatpickr from 'flatpickr';
// https://github.com/flatpickr/flatpickr/tree/master/src/l10n
import { English } from 'flatpickr/dist/l10n/default.js';
import { German } from 'flatpickr/dist/l10n/de.js';
import { Italian } from 'flatpickr/dist/l10n/it.js';
import { French } from 'flatpickr/dist/l10n/fr.js';
import { Spanish } from 'flatpickr/dist/l10n/es.js';
import { flatpickrToToubizDatepickerAdapter } from '@newland/assets-neos/Products/date-picker/adaptor/flatpickr';


const initFlatpickrs = () => {
    const datePickerContainers = document.querySelectorAll('[data-flatpickr-container]');

    if (datePickerContainers.length > 0) {
        // Override Sunday being firstDayOfWeek -> now Monday
        flatpickr.l10ns.en.firstDayOfWeek = 1;

        const flatpickrLanguage = document.documentElement.getAttribute('lang');
        // Set default language
        let dateLocale = English;
        // Check if data attribute is in dom and set new language
        if (flatpickrLanguage) {
            dateLocale = flatpickrLanguage;
        }

        for (const datePicker of datePickerContainers) {
            const dateInputFrom = datePicker.querySelector('[data-flatpickr\\.from]');
            const dateInputTo = datePicker.querySelector('[data-flatpickr\\.to]');
            const dateUnknown = datePicker.querySelector('[data-flatpickr\\.form-param]');

            if (dateInputTo && dateInputFrom && dateUnknown) {
                const dateInputToInstance = dateInputTo.flatpickr({
                    dateFormat: 'd.m.Y',
                    disableMobile: true,
                    locale: dateLocale,
                });

                dateInputFrom.flatpickr({
                    dateFormat: 'd.m.Y',
                    disableMobile: true,
                    locale: dateLocale,
                    minDate: 'today',
                    // eslint-disable-next-line
                    onChange: function (selectedDates) {
                        const newToDate = selectedDates[0].fp_incr(1);
                        dateInputTo.value = newToDate;
                        dateInputToInstance.set('minDate', newToDate);
                        dateInputToInstance.setDate(newToDate);
                        dateInputToInstance.open();
                        if (dateUnknown) {
                            dateUnknown.remove();
                        }
                    },
                });

                flatpickrToToubizDatepickerAdapter(datePicker, dateInputFrom, dateInputTo);
            }
        }
    }
};

onPageLoadComplete(() => initFlatpickrs());
