(function ($, Drupal, once) {
    let jobLabel = "";

    class TemplatesOrServicesForm {
        constructor($formField) {
            this.targetLanguageSelectField = $formField.find('select[data-drupal-selector="edit-target-language"]');
            this.providerSelectField = $formField.find('select[data-drupal-selector="edit-translator"]');
            this.$projectTemplatesSelectField = $formField.find('select[data-project-templates]');

            this.configurableFields = {
                workAreaSelectField: $formField.find('select[data-drupal-selector="edit-settings-work-area"]'),
                translationMemorySelectField: $formField.find('select[data-drupal-selector="edit-settings-translation-memory"]'),
                termBaseSelectField: $formField.find('select[data-drupal-selector="edit-settings-term-base"]'),
                invoicingAccountSelectField: $formField.find('select[data-drupal-selector="edit-settings-invoicing-account"]')
            };
            this.$tmgmtJobLabelField = $formField.find('input[data-drupal-selector="edit-label-0-value"]');
            this.$bundleCheckBox = $formField.find('input[data-drupal-selector="edit-settings-bundling"]');
            this.$submitAll = $formField.find('input[data-drupal-selector="edit-submit-all"]');
            this.$deadlineField = $formField.find('input[data-drupal-selector="edit-settings-deadline"]');
            this.cacheCurrentDeadlineValue();

            this.projectTemplateSettings = this.loadProjectTemplateSettings();
            this.languageMappings = this.loadLanguageMappings();
            this.removeDuplicatedCKEditorInstances();
            this.attachEventHandlers();
            this.storeJobLabel();
        }

        static get templateAttributePrefix() {
            return 'template_';
        }

        loadLanguageMappings() {
            return this.$projectTemplatesSelectField.data('languageMappings');
        }

        loadProjectTemplateSettings() {
            return this.$projectTemplatesSelectField.data('projectTemplates');
        }

        storeJobLabel() {
            let _this = this;
            this.$tmgmtJobLabelField.on('keyup', function () {
                jobLabel = _this.$tmgmtJobLabelField.val();
            });
        }

        restoreJobLabel() {
            let _this = this;
            let jobLabelTitle = jobLabel;

            if (jobLabelTitle === "") {
                return;
            }

            setTimeout(function () {
                _this.$tmgmtJobLabelField.val(jobLabelTitle);
            }, 2000);
        }

        attachEventHandlers() {
            let _this = this;

            this.targetLanguageSelectField.on('change', function () {
                _this.restoreJobLabel();

                setTimeout(function() {
                    _this.removeDuplicatedCKEditorInstances();
                }, 2000);
            });

            this.providerSelectField.on('change', function () {
                _this.restoreJobLabel();
            });

            this.$projectTemplatesSelectField.on('change', function () {
                const selectedIdAttr = $(this).val();

                _this.clearRestrictions();

                if (_this.templateIsSelected(selectedIdAttr)) {
                    const selectedId = selectedIdAttr.slice(TemplatesOrServicesForm.templateAttributePrefix.length);
                    _this.selectProjectTemplate(parseInt(selectedId));
                } else {
                    _this.clearFields();
                }

                _this.restoreJobLabel();
            });
            this.$projectTemplatesSelectField.change();

            this.$deadlineField.on('change', function () {
                _this.cacheCurrentDeadlineValue();
            });

            this.$bundleCheckBox.on('change', function () {
                if ($(this).is(':checked')) {
                    _this.$submitAll.prop('checked', true);
                }
            });

            this.$submitAll.on('change', function () {
                if (!$(this).is(':checked')) {
                    _this.$bundleCheckBox.prop('checked', false);
                }
            });

            this.$bundleCheckBox.trigger('change');
        }

        clearFields() {
            this.changeTMGMTJobLabel(null);
            this.restoreDeadlineFromCache();
            this.changeBriefing(null);
            this.enableDropdowns();
        }

        selectProjectTemplate(selectedPlatformId) {
            const projectTemplateSettings = this.projectTemplateSettings.find(x => x.projectTemplate.platformId === selectedPlatformId);

            if (projectTemplateSettings) {
                this.restrictWorkArea(projectTemplateSettings.workArea?.item_id, projectTemplateSettings.workArea?.name);

                if (projectTemplateSettings.translationMemory != null) {
                    this.restrictTranslationMemory(projectTemplateSettings.translationMemory?.item_id, projectTemplateSettings.translationMemory?.name);
                }

                if (projectTemplateSettings.termBase != null) {
                    this.restrictTermBase(projectTemplateSettings.termBase?.item_id, projectTemplateSettings.termBase?.name);
                }

                this.restrictInvoicingAccount(projectTemplateSettings.invoicingAccount?.item_id, projectTemplateSettings.invoicingAccount?.name);
                this.disableDropdowns();

                const projectTemplate = projectTemplateSettings.projectTemplate;

                this.changeTMGMTJobLabel(projectTemplate.projectName);
                this.changeBriefing(projectTemplate.briefingToLanguageWire);
            }
        }

        clearRestrictions() {
            this.resetConfigurableFields();
        }

        resetConfigurableFields() {
            for (const fieldName in this.configurableFields) {
                const field = this.configurableFields[fieldName];

                field.find('option').each(function () {
                    $(this).removeAttr("disabled");
                    $(this).removeAttr("selected");
                    $(this).css("display", "block");
                });

                field.find('option').remove(".temp");

                field.removeAttr("readonly");
            }
        }

        restrictWorkArea(workAreaId, workAreaName) {
            const field = this.configurableFields['workAreaSelectField'];
            this.exclusivelySelectItem(field, workAreaId, workAreaName);
        }

        restrictTranslationMemory(translationMemoryId, translationMemoryName) {
            const field = this.configurableFields['translationMemorySelectField'];
            this.exclusivelySelectItem(field, translationMemoryId, translationMemoryName);
        }

        restrictTermBase(termBaseId, termBaseName) {
            const field = this.configurableFields['termBaseSelectField'];
            this.exclusivelySelectItem(field, termBaseId, termBaseName);
        }

        restrictInvoicingAccount(invoicingAccountId, invoicingAccountName) {
            const selectField = this.configurableFields['invoicingAccountSelectField'];
            this.exclusivelySelectItem(selectField, invoicingAccountId, invoicingAccountName);
        }

        changeTMGMTJobLabel(name) {
            const nameOrDefault = name ? name : "";
            this.$tmgmtJobLabelField.val(nameOrDefault);
        }

        changeDeadline(deadline) {
            let formattedDate = "";

            if (deadline != null) {
                const d = new Date(deadline);
                formattedDate = d.toISOString().split("T")[0];
            }

            this.$deadlineField.val(formattedDate).change();
        }

        changeBriefing(briefingHtml) {
            const ckeditor = this.getCKEditorInstance();

            if (!!ckeditor) {
                ckeditor.setData(briefingHtml ?? "");
            }
        }

        exclusivelySelectItem(selectField, itemId, itemName) {
            selectField.find('option').removeAttr("selected");

            if (!!itemId) {
                selectField.append($('<option>', {
                    value: itemId,
                    text: itemName ?? '',
                    class: "temp",
                    selected: "selected"
                }));
            }

            selectField.prop("readonly", "readonly");
        }

        templateIsSelected(selectedIdAttr) {
            return selectedIdAttr.indexOf(TemplatesOrServicesForm.templateAttributePrefix) !== -1;
        }

        disableDropdowns() {
            $(this.configurableFields['workAreaSelectField']).prop('disabled', true);
            $(this.configurableFields['translationMemorySelectField']).prop('disabled', true);
            $(this.configurableFields['termBaseSelectField']).prop('disabled', true);
            $(this.configurableFields['invoicingAccountSelectField']).prop('disabled', true);
        }

        enableDropdowns() {
            $(this.configurableFields['workAreaSelectField']).prop('disabled', false);
            $(this.configurableFields['translationMemorySelectField']).prop('disabled', false);
            $(this.configurableFields['termBaseSelectField']).prop('disabled', false);
            $(this.configurableFields['invoicingAccountSelectField']).prop('disabled', false);
        }

        cacheCurrentDeadlineValue() {
            this.deadlineValueCache = this.$deadlineField.val() || null;
        }

        restoreDeadlineFromCache() {
            this.changeDeadline(this.deadlineValueCache);
        }

        getCKEditorInstance() {
            if (window.hasOwnProperty('CKEDITOR')) {
                for (const instancesKey in CKEDITOR.instances) {
                    if (instancesKey.includes('settings-briefing')) {
                        return CKEDITOR.instances[instancesKey];
                    }
                }
            }

            if (window.hasOwnProperty('CKEditor5')) {
                const briefingElementsWithCKE = $('.ck-editor__editable')
                    .closest('[data-drupal-selector=edit-settings-briefing]')
                    .find('.ck-editor__editable');

                if (briefingElementsWithCKE.length > 0) {
                    return briefingElementsWithCKE[0].ckeditorInstance;
                }
            }

            return null;
        }

        removeDuplicatedCKEditorInstances() {
            if (window.hasOwnProperty('CKEditor5')) {
                const briefingElementsCKE = $('.ck-editor');

                if (briefingElementsCKE.length > 1) {
                    briefingElementsCKE[1].remove();
                }
            }
        }
    }

    Drupal.behaviors.languagewire_tmgmt_connector = {
        attach: function (context, settings) {
            once('languagewire_tmgmt_connector', '#tmgmt-ui-translator-settings', context).forEach(function () {
                let checkoutForm = $('.tmgmt-job-edit-form').first();
                new TemplatesOrServicesForm(checkoutForm);
            });
        }
    };
})(jQuery, Drupal, once);
