import IMask from "imask";
class InstallmentRule {
    constructor() {
        this.handleCardRates();
        this.controllFields();
        this.createRateByInstallmentsFields();
        this.fillInstallmentsFields();
        this.updateInstallmentFields();
        this.setMasks();
        this.handleMaxInstallmentsChange();
    }

    handleMaxInstallmentsChange() {
        const maxInstallmentsField = document.querySelector('#wc_koin_max_installments');
        const minInstallmentsField = document.querySelector('#wc_koin_min_installments');
        const refreshInstallmentFields = () => {
            this.removeInstallmentsFields();
            this.createRateByInstallmentsFields();
            this.fillInstallmentsFields();
            this.updateInstallmentFields();
        };
        if (maxInstallmentsField) {
            maxInstallmentsField.addEventListener('input', refreshInstallmentFields);
        }
        if (minInstallmentsField) {
            minInstallmentsField.addEventListener('input', refreshInstallmentFields);
        }
    }

    removeInstallmentsFields() {
        const field = document.querySelector('#wc_koin_rate_transfer_by_installments');
        const parent = field ? field.parentElement : null;
        const oldContext = parent ? parent.querySelector('.koin-installments-container-context') : null;
        if (oldContext) {
            oldContext.remove();
        }
    }

    handleCardRates() {
        const rateType = document.querySelector('#wc_koin_rate_transfer_type');

        if (rateType) {
            rateType.addEventListener('change', () => {
                this.controllFields();
            });
        }
    }

    setMasks() {
        ['#wc_koin_rate_transfer_simple', '#wc_koin_min_installment_value'].forEach(selector => {
            const element = document.querySelector(selector);
            if (element) {
                this.setFeeFieldMask(element);
            }
        });
    }

    controllFields() {
        const rateType = document.querySelector('#wc_koin_rate_transfer_type');

        if (rateType) {
            switch (rateType.value) {
                case '1':
                    this.showSimpleRate();
                    break;
                case '2':
                    this.showRateByInstallment();
                    break;
                default:
                    this.hideTransferFields();
                    break;
            }
        }
    }

    hideTransferFields() {
        const elements = [
            document.querySelector('#wc_koin_rate_transfer_format'),
            document.querySelector('#wc_koin_rate_transfer_simple'),
            document.querySelector('#wc_koin_rate_transfer_by_installments')
        ];

        elements.forEach(element => {
            const parent = element.parentElement.parentElement;
            if (parent) {
                parent.classList.add('deactive');
            }
        });
    }

    showSimpleRate() {
        this.hideTransferFields();

        const elements = [
            document.querySelector('#wc_koin_rate_transfer_format'),
            document.querySelector('#wc_koin_rate_transfer_simple')
        ];

        elements.forEach(element => {
            const parent = element.parentElement.parentElement;
            if (parent) {
                parent.classList.remove('deactive');
            }
        });
    }

    showRateByInstallment() {
        this.hideTransferFields();

        const elements = [
            document.querySelector('#wc_koin_rate_transfer_format'),
            document.querySelector('#wc_koin_rate_transfer_by_installments')
        ];

        elements.forEach(element => {
            const parent = element.parentElement.parentElement;
            if (parent) {
                parent.classList.remove('deactive');
            }
        });
    }

    createRateByInstallmentsFields() {
        const field = document.querySelector('#wc_koin_rate_transfer_by_installments');
        const maxInstallmentsField = document.querySelector('#wc_koin_max_installments');
        const minInstallmentsField = document.querySelector('#wc_koin_min_installments');
        let maxInstallments = 72;
        let minInstallments = 1;
        if (maxInstallmentsField && maxInstallmentsField.value) {
            const parsed = parseInt(maxInstallmentsField.value, 10);
            if (!isNaN(parsed) && parsed > 0 && parsed <= 72) {
                maxInstallments = parsed;
            }
        }
        if (minInstallmentsField && minInstallmentsField.value) {
            const parsedMin = parseInt(minInstallmentsField.value, 10);
            if (!isNaN(parsedMin) && parsedMin > 0 && parsedMin <= maxInstallments) {
                minInstallments = parsedMin;
            }
        }

        if (field) {
            field.style = 'display: none';
            const parent = field.parentElement;

            const context = document.createElement("div");
            context.classList.add('koin-installments-container-context');

            for (let index = minInstallments; index <= maxInstallments; index++) {
                const span = document.createElement("span");
                span.innerText = index;

                const input = document.createElement("input");
                input.setAttribute("data-installment", index);
                input.classList.add('koin-installments-fields');
                this.setFeeFieldMask(input);

                const div = document.createElement("div");
                div.classList.add('koin-installments-container-fields');

                div.appendChild(span);
                div.appendChild(input);

                context.appendChild(div);
            }

            parent.appendChild(context);
        }
    }

    setFeeFieldMask(field) {
        if (!field) return;
        IMask(
            field,
            {
                mask: [
                    { mask: '' },
                    {
                        mask: 'num',
                        lazy: false,
                        blocks: {
                            num: {
                                mask: Number,
                                scale: 2,
                                padFractionalZeros: true,
                                radix: '.',
                                mapToRadix: [','],
                            }
                        }
                    }
                ]
            }
        );
    }

    fillInstallmentsFields() {
        const field = document.querySelector('#wc_koin_rate_transfer_by_installments');
        const data = JSON.parse(field.value);

        if (data) {
            const installments = document.querySelectorAll('.koin-installments-fields');

            installments.forEach(element => {
                const installmentNumber = element.getAttribute('data-installment');
                if (data[installmentNumber] !== undefined) {
                    element.value = data[installmentNumber];
                } else {
                    data[installmentNumber] = '0.00';
                    element.value = '0.00';
                }
            });

            field.value = JSON.stringify(data);
        }
    }

    updateInstallmentFields() {
        const installments = document.querySelectorAll('.koin-installments-fields');
        const field = document.querySelector('#wc_koin_rate_transfer_by_installments');
        const data = JSON.parse(field.value);

        installments.forEach(element => {
            element.addEventListener('change', () => {
                const installmentNumber = element.getAttribute('data-installment');
                if (data[installmentNumber] === undefined) {
                    data[installmentNumber] = '0.00';
                }
                data[installmentNumber] = element.value;
                field.value = JSON.stringify(data);
            });
        });
    }
}

document.addEventListener("DOMContentLoaded", () => {
    const koin = document.querySelector(".koin-installment-rule");
    if (koin) {
        new InstallmentRule;
    }
});
