import $ from 'jquery';
import flatpickr from 'flatpickr';
import { German } from 'flatpickr/dist/l10n/de.js';
import { French } from 'flatpickr/dist/l10n/fr.js';
import { Italian } from 'flatpickr/dist/l10n/it.js';
import { Bulgarian } from 'flatpickr/dist/l10n/bg.js';
import { Czech } from 'flatpickr/dist/l10n/cs.js';
import { Danish } from 'flatpickr/dist/l10n/da.js';
import { Greek } from 'flatpickr/dist/l10n/gr.js';
import { Spanish } from 'flatpickr/dist/l10n/es.js';
import { Estonian } from 'flatpickr/dist/l10n/et.js';
import { Croatian } from 'flatpickr/dist/l10n/hr.js';
import { Hungarian } from 'flatpickr/dist/l10n/hu.js';
import { Icelandic } from 'flatpickr/dist/l10n/is.js';
import { Lithuanian } from 'flatpickr/dist/l10n/lt.js';
import { Latvian } from 'flatpickr/dist/l10n/lv.js';
import { Macedonian } from 'flatpickr/dist/l10n/mk.js';
import { Norwegian } from 'flatpickr/dist/l10n/no.js';
import { Dutch } from 'flatpickr/dist/l10n/nl.js';
import { Polish } from 'flatpickr/dist/l10n/pl.js';
import { Portuguese } from 'flatpickr/dist/l10n/pt.js';
import { Romanian } from 'flatpickr/dist/l10n/ro.js';
import { Russian } from 'flatpickr/dist/l10n/ru.js';
import { Slovak } from 'flatpickr/dist/l10n/sk.js';
import { Slovenian } from 'flatpickr/dist/l10n/sl.js';
import { Serbian } from 'flatpickr/dist/l10n/sr.js';
import { Swedish } from 'flatpickr/dist/l10n/sv.js';
import { Turkish } from 'flatpickr/dist/l10n/tr.js';

(function($) {

    let state = {
        isCompany: false
    }

    const Front = {

        init: () => {

            if( jQuery('body').hasClass('woocommerce-order-pay') && jQuery('.woocommerce-notices-wrapper').length > 0 ) {
                jQuery('html, body').animate({
                        scrollTop: jQuery('.woocommerce-notices-wrapper').offset().top,
                }, 800);

                if( jQuery('#payment_method_cembrapay').length > 0 ) {
                    jQuery('#payment_method_cembrapay').trigger('click');
                }
            }
            
            if( 1 == cembrapay.autoSelectGateway && jQuery('.payment_method_cembrapay').length > 0 ) {
	
                setTimeout( () => {
                    
                    jQuery('#payment_method_cembrapay').prop('checked', true);
                    jQuery('.payment_box').fadeOut(function() {
                        jQuery('.payment_box.payment_method_cembrapay').fadeIn();
                    });

                }, 1000);

                if( jQuery('#billing_company').length > 0 && jQuery('#billing_company').val() ) {
                    state.isCompany = true;
                }
        
            }

            const enableBirthdateDatepicker = setInterval( () => {
                
                if( jQuery('#cembrapay_birthdate_datepicker').length > 0 ) {

                    const lang = cembrapay.locale || 'en';

                    const locales = {
                        de: German,
                        fr: French,
                        it: Italian,
                        bg: Bulgarian,
                        cs: Czech,
                        da: Danish,
                        gr: Greek,
                        es: Spanish,
                        et: Estonian,
                        hr: Croatian,
                        hu: Hungarian,
                        is: Icelandic,
                        lt: Lithuanian,
                        lv: Latvian,
                        mk: Macedonian,
                        no: Norwegian,
                        nl: Dutch,
                        pl: Polish,
                        pt: Portuguese,
                        ro: Romanian,
                        ru: Russian,
                        sk: Slovak,
                        sl: Slovenian,
                        sr: Serbian,
                        sv: Swedish,
                        tr: Turkish
                    };

                    const selectedLocale = locales[lang] || flatpickr.l10ns.default;

                    const element = document.getElementById('cembrapay_birthdate_datepicker');

                    if (element._flatpickr) {
                        clearInterval(enableBirthdateDatepicker);
                        return;
                    }

                    const today = new Date();

                    console.log(cembrapay.defaultBirthdate, cembrapay.dateFormat);

                    flatpickr('#cembrapay_birthdate_datepicker', {
                        dateFormat: cembrapay.dateFormat || 'd.m.Y',
                        maxDate: new Date(today.getFullYear(), today.getMonth(), today.getDate()),
                        // defaultDate: cembrapay.defaultBirthdate ? cembrapay.defaultBirthdate : '1990-01-01',
                        onOpen: function(selectedDates, dateStr, instance) {
                            if (!selectedDates.length) {
                            // No date selected → jump to March 2, 1970
                                instance.jumpToDate(cembrapay.defaultBirthdate || '1990-01-01'); // Month is zero-based
                            }
                        },
                        locale: {
                            ...selectedLocale,
                            firstDayOfWeek: 1
                        }
                    });

                    // setTimeout( () => {
                    //     clearInterval(enableBirthdateDatepicker);
                    // }, 2000);

                    // jQuery( "#cembrapay_birthdate_datepicker" ).datepicker({
                    //     dateFormat: 'yy-mm-dd',
                    //     changeMonth: true,
                    //     changeYear: true,
                    //     yearRange: '-100:+0',
                    //     defaultDate: 0 == cembrapay.allowUnderage && cembrapay.underageThreshold ? new Date(today.getFullYear() - parseInt( cembrapay.underageThreshold ), today.getMonth(), today.getDate()) : today
                    // });

                }

            }, 1000);

            const processInstallments = setInterval( () => {

                if( jQuery('.cembrapay-installment').length > 0 ) {
                    Front.processInstallments();
                }

            }, 1000);

            const initInvoiceType = setInterval( () => {

                // if( 
                //     '' != jQuery('label[for="cembrapay-invoice-type-post"]').text() 
                //     && '' != jQuery('label[for="cembrapay-invoice-type-email"]').text()
                // ) {
                //     clearInterval(initInvoiceType);
                // }
                
                Front.processInvoiceType();

            }, 1000);

            Front.initBillingCompany();

            // setTimeout( () => {
            //     clearInterval(enableBirthdateDatepicker);
            //     clearInterval(processInstallments);
            //     clearInterval(initInvoiceType);
            // }, 20000);

        },
        initBillingCompany: () => {

            const initBillingCompany = setInterval( () => {

                if( jQuery('#billing_company').val() ) {
                    state.isCompany = true;
                    if( jQuery('.cembrapay-company-reg-container').length > 0 ) {
                        jQuery('.cembrapay-company-reg-container').show();
                    }
                    jQuery('.cembrapay-birthdate-container').hide();
                } else {
                    if( jQuery('.cembrapay-company-reg-container').length > 0 ) {
                        jQuery('.cembrapay-company-reg-container').hide();
                    }
                    jQuery('.cembrapay-birthdate-container').show();
                }

                // clearInterval(initBillingCompany);

            }, 1000);

            // setTimeout( () => {
            //     clearInterval(initBillingCompany);
            // }, 20000);

        },
        processInstallments: () => {

            if( ! jQuery('.cembrapay-installment').length ) {
                return;
            }

            jQuery('.cembrapay-installment').parent().hide();

            jQuery('.cembrapay-installment').each(function(idx, installment){

                const target = jQuery(installment).data('for');

                if( state.isCompany ) {
                    if( 'b2b' === target || 'all' === target) {
                        jQuery(installment).parent().show();
                    }
                    if( 'b2c' === target ) {
                        jQuery(installment).parent().hide();
                    }
                }

                if( ! state.isCompany ) {
                    if( 'b2b' === target ) {
                        jQuery(installment).parent().hide();
                    }
                    if( 'b2c' === target || 'all' === target ) {
                        jQuery(installment).parent().show();
                    }
                }

            });

        },
        onBirthdateFieldChange: (trigger) => {

            const fieldId = trigger.attr('id');

            switch( fieldId ) {
                case 'cembrapay_birthdate_day':
                    if( trigger.val() && trigger.val() <= 0 ) {
                        trigger.val('01');
                    }
                    if( trigger.val() && trigger.val() > 31 ) {
                        trigger.val('31');
                    }
                    if(trigger.val().length > 2) {
                        trigger.val(trigger.val().slice(0, 2));
                    }
                break;
                case 'cembrapay_birthdate_month':
                    if( trigger.val() && trigger.val() <= 0 ) {
                        trigger.val('01');
                    }
                    if( trigger.val() && trigger.val() > 12 ) {
                        trigger.val('12');
                        return false;
                    }
                    if(trigger.val().length > 2) {
                        trigger.val(trigger.val().slice(0, 2));
                    }
                break;
                case 'cembrapay_birthdate_year':
                    if( trigger.val() && trigger.val() <= 0 ) {
                        trigger.val('1970');
                    }
                    if(trigger.val().length > 4) {
                        trigger.val(trigger.val().slice(0, 4));
                    }
                break;
            }
            
        },
        onBillingCompanyChange: (trigger) => {
            
            state.isCompany = trigger.val() ? true : false;

            true === state.isCompany ? jQuery('.cembrapay-company-reg-container').show() : jQuery('.cembrapay-company-reg-container').hide();
            
            Front.initBillingCompany();
            Front.processInstallments();

        },
        processInvoiceType: () => {

            if( ! jQuery('.cembrapay-invoice-type').length ) {
                return;
            }

            if( jQuery('#cembrapay-invoice-type-post').length > 0 ) {

                let address = '';
                
                if( jQuery('#billing_address_1').length > 0 ) {
                    address += jQuery('#billing_address_1').val();
                }

                if( cembrapay.orderPayOrder && cembrapay.orderPayOrder.billingAddress1 ) {
                    address += cembrapay.orderPayOrder.billingAddress1;
                }

                if( jQuery('#billing_address_2').length > 0 ) {
                    address += ' ' + jQuery('#billing_address_2').val();
                }

                if( cembrapay.orderPayOrder && cembrapay.orderPayOrder.billingAddress2 ) {
                    address += ' ' + cembrapay.orderPayOrder.billingAddress2;
                }

                if( jQuery('#billing_postcode').length > 0 ) {
                    address += ', ' + jQuery('#billing_postcode').val();
                }

                if( cembrapay.orderPayOrder && cembrapay.orderPayOrder.billingPostcode ) {
                    address += ', ' + cembrapay.orderPayOrder.billingPostcode;
                }

                if( jQuery('#billing_city').length > 0 ) {
                    address += ' ' + jQuery('#billing_city').val();
                }

                if( cembrapay.orderPayOrder && cembrapay.orderPayOrder.billingCity ) {
                    address += ' ' + cembrapay.orderPayOrder.billingCity;
                }

                if( jQuery('#billing_state').length > 0 ) {
                    address += ', ' + jQuery('#billing_state').val();
                }

                if( cembrapay.orderPayOrder && cembrapay.orderPayOrder.billingState ) {
                    address += ', ' + cembrapay.orderPayOrder.billingState;
                }

                if( jQuery('#billing_country').length > 0 ) {
                    address += ', ' + jQuery('#billing_country').val();
                }

                if( cembrapay.orderPayOrder && cembrapay.orderPayOrder.billingCountry ) {
                    address += ', ' + cembrapay.orderPayOrder.billingCountry;
                }

                if( address ) {
                    jQuery('label[for="cembrapay-invoice-type-post"] span.value').text(address);
                }

            }

            if( jQuery('#cembrapay-invoice-type-email').length > 0 ) {
                    
                let email = '';
                if( jQuery('#billing_email').length > 0 ) {
                    email = jQuery('#billing_email').val();
                }

                if( cembrapay.orderPayOrder && cembrapay.orderPayOrder.billingEmail ) {
                    email = cembrapay.orderPayOrder.billingEmail;
                }

                if( email ) {
                    jQuery('label[for="cembrapay-invoice-type-email"] span.value').text(email);
                }
                
            }

        }

    }

    jQuery(function() {

        Front.init();

        jQuery('#billing_company').on('change', function() {
            Front.onBillingCompanyChange( jQuery(this) );
        });

        jQuery('.woocommerce-billing-fields input, .woocommerce-billing-fields select').on('change', function(evt) {
            Front.processInvoiceType();
        });

        jQuery('body').on('change', '.birthdate_field', function(evt) {
            Front.onBirthdateFieldChange( jQuery(this) );
        });

    });

})(jQuery);