var formType = 'aa-content-reference';
function initPlugin(el, defaultOptions, libs) {
    var formWrap = el.classList.contains(formType) ? el : el.closest('.' + formType);
    if (formWrap === null) {
        console.error('could not create ' + formType + ' plugin');
        return;
    }

    var formTypeEl = formWrap.querySelector(':scope .aa-content-ref-formType');
    var searchResultsEl = formWrap.querySelector(':scope .aa-content-ref-search-results');
    var contentReferenceIdEl = formWrap.querySelector(':scope .aa-content-ref-pk');
    var contentIdEl = formWrap.querySelector(':scope .aa-content-ref-id');
    var actionEl = formWrap.querySelector(':scope .aa-content-ref-action');
    var localeEl = formWrap.querySelector(':scope .aa-content-ref-locale');
    var deleteEl = formWrap.querySelector(':scope .aa-content-ref-delete');
    var createPlugin = function () {
        return {
            formTypeEl: formTypeEl,
            // searchEl: searchEl,
            searchResultsEl: searchResultsEl,
            contentReferenceIdEl: contentReferenceIdEl,
            contentIdEl: contentIdEl,
            actionEl: actionEl,
            localeEl: localeEl,
            deleteEl: deleteEl,
            apiInitUrl: '/admin/fr/content-reference/init',
            apiSearchUrl: '/admin/fr/content-reference/search',
            // values
            term: null,
            contentReferenceId: null,
            contentformType: null,
            contentAction: null,
            contentLocale: null,
            contentId: null,
            // utils
            searchDebounce: null,
            searchDebounceTime: 450,
            initialValue: null,
            init() {
                this.contentReferenceId = this.contentReferenceIdEl.value;
                this.contentId = this.contentIdEl.value;
                this.refreshInputValues();

                this.initialValue = {
                    contentformType: this.contentformType,
                    contentAction: this.contentAction,
                    contentLocale: this.contentLocale,
                    contentId: this.contentId,
                    contentReferenceId: this.contentReferenceId,
                    choice: null,
                };

                if (this.initialValue.contentformType && this.initialValue.contentId) {
                    setTimeout(() => {
                        var choicesPromise = fetch(this.buildApiInitUrl())
                            .then(response => response.json())
                            .then((json) => {
                                var choices = [];

                                if (json.content) {
                                    this.initialValue.choice = json.content;
                                    choices = [
                                        {
                                            label: this.initialValue.choice.label,
                                            value: this.initialValue.choice.value,
                                            selected: true,
                                        },
                                    ];
                                }

                                return choices;
                            });
                        this.updateChoices(choicesPromise);
                    }, 200);// error triggered here, TODO: find cause (related to placeholder ?)
                }

                // listeners
                this.formTypeEl.addEventListener('change', this.triggerSearchListener.bind(this))
                this.searchResultsEl.addEventListener('search', this.triggerSearchListener.bind(this))
                this.searchResultsEl.addEventListener('choice', this.selectItem.bind(this))
            },
            updateChoices(promise) {
                this.searchResultsEl.aaFormComponent['aa-ft-select-rich'].setChoices(async () => {
                    try {
                        return await promise
                    } catch (err) {
                        console.error(err);
                    }
                }, 'value', 'label', true);

                return promise;
            },
            buildApiInitUrl() {
                var url = new URL(window.location.protocol + "//" + window.location.hostname + this.apiInitUrl);
                url.searchParams.append('content_reference_id', this.initialValue.contentReferenceId);

                return url.toString();
            },
            buildApiSearchUrl() {
                var url = new URL(window.location.protocol + "//" + window.location.hostname + this.apiSearchUrl);
                url.searchParams.append('content_formType', this.contentformType);
                url.searchParams.append('term', this.term);

                return url.toString();
            },
            refreshInputValues() {
                this.term = this.searchResultsEl.aaFormComponent['aa-ft-select-rich'].input.value;

                this.contentformType = this.formTypeEl.value;
                this.contentLocale = this.localeEl.value;
                this.contentAction = this.actionEl.value;

            },
            selectItem(event) {
                this.refreshInputValues();
                var id = event.detail.choice.value;
                var label = event.detail.choice.label;
                this.contentId = id;
                // set values back in html
                this.mirrorToHtml();
            },
            mirrorToHtml() {
                this.contentIdEl.value = this.contentId;
            },
            triggerSearchListener(event) {
                this.refreshInputValues();
                if (this.searchDebounce) {
                    clearTimeout(this.searchDebounce);
                }
                this.searchDebounce = setTimeout(() => {
                    this.search();
                }, this.searchDebounceTime);
            },
            search() {
                if (!this.contentformType || !this.term || this.term.length === 0) {
                    return;
                }
                console.log(this);
                var choicesPromise = fetch(this.buildApiSearchUrl())
                    .then(response => response.json())
                    .then((json) => {
                        // wrap.style.display = '';
                        console.log(json);
                        var choices = [];
                        for (var i in json.contents) {
                            var content = json.contents[i];
                            choices.push(content);
                        }
                        return choices;
                    });
                this.updateChoices(choicesPromise);
            }
        }
    };


    var plugin = createPlugin();
    plugin.init();

    return plugin;
}

// document.body.addEventListener('aa_form_register_custom_type', (e)=> {
//     e.registerCustomType(formType, initPlugin);
// })
AAForm.addTypeHandler(formType, initPlugin);