function getCookieValue() {
    const cookie = document.cookie.split(';').find(str => str.trim().startsWith('forest_session_data'));
    if (cookie) {
        return cookie.slice(cookie.indexOf('=') + 1);
    }
    return '';
}
function activateLeadsExport(event) {
    event.stopPropagation();
    component.actions.exportLeads();
}
function handleExportLeadsOpenButtonClick() {
    const intervalId = setInterval(() => {
        const exportLeadsActivateButton = document.querySelector(exportLeadsActivateButtonQuery);
        if (exportLeadsActivateButton) {
            clearInterval(intervalId);
            exportLeadsActivateButton.addEventListener('click', activateLeadsExport);
        }
    }, 100);
}
function handleGetRandomLeadsClick(event) {
    event.preventDefault();
    event.stopPropagation();
    const actionsList = document.querySelector(actionsListQuery);
    if (actionsList && actionsButton) {
        actionsList.remove();
        actionsButton.click();
    }
    component.actions.getRandomLeads();
}
function handleActionsButtonClick() {
    const intervalId = setInterval(() => {
        const exportLeadsOpenButton = document.querySelector(exportLeadsOpenButtonQuery);
        const getRandomLeadsButton = document.querySelector(getRandomLeadsButtonQuery);
        if (exportLeadsOpenButton) {
            clearInterval(intervalId);
            exportLeadsOpenButton.addEventListener('click', handleExportLeadsOpenButtonClick);
            if (getRandomLeadsButton) {
                getRandomLeadsButton.addEventListener('click', handleGetRandomLeadsClick);
            }
        }
    }, 100);
}
function getParams(isExport = false) {
    const { sortedField, searchValue, collection: { mainView: { content } }, customerId } = component;
    const { filtersObject, currentPage, orderByNumber } = component;
    const params = {
        sort: 'person.fullName',
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
        'page[number]': currentPage || 1,
        'page[size]': content && content.recordsPerPage ? content.recordsPerPage : 15,
    };
    if (isExport) {
        params['page[number]'] = 1;
        params['page[size]'] = 100;
    }
    if (filtersObject) {
        params.filters = JSON.stringify(filtersObject);
    }
    if (sortedField) {
        const { field, order, referenceSortingField: refField } = sortedField;
        params.sort = (order === 'ascending' ? '' : '-') + field + (refField ? `.${refField}` : '');
    }
    if (customerId) {
        params.customerId = customerId;
    }
    if (orderByNumber) {
        params.orderByNumber = orderByNumber;
    }
    if (searchValue && searchValue.length) {
        params.search = searchValue;
    }
    return params;
}
export default Component.extend(SmartViewMixin, {
    store: service(),
    customerId: '',
    inputValue: '',
    filtersObject: null,
    orderByNumber: 0,
    aggregators: [],
    appliedFiltersEntries: [],
	init(...args) {
        this._super(...args);
        this.set('fetchRecords', this.actions.fetchData);
        if (document.getElementById(customerFieldId)) {
            return;
        }
        component = this;
        const editLayoutBtn = document.getElementById(editLayoutButtonId);
        const actionContainer = document.querySelector('.c-beta-header__actions-right');
        const customerField = document.createElement('div');
        customerField.id = customerFieldId;
        customerField.className = 'c-beta-label__input';
        customerField.innerHTML = `
			<div class="c-row-belongs-to ">
                <span id="${customerFieldSpanId}"
                    class="c-row-belongs-to__input-container c-typeahead-field c-typeahead-field--relative">
                    <svg style="visibility:hidden" id="leadtime-customer-input-loader"
                        class="c-beta-loader c-beta-loader--primary c-typeahead-field__loader"
                        width="40px" height="40px" xmlns="http://www.w3.org/2000/svg"
                        viewBox="0 0 100 100" preserveAspectRatio="xMidYMid">
						<circle class="c-beta-loader__circle" cx="50" cy="50" fill="none" stroke-width="10"
                            r="35" stroke-dasharray="164.93361431346415 56.97787143782138"
                            transform="rotate(305.844 50 50)">
    						<animateTransform attributeName="transform" calcMode="linear" values="0 50 50;360 50 50"
                                keyTimes="0;1" dur="1s" begin="0s" repeatCount="indefinite" type="rotate">
                            </animateTransform>
  						</circle>
					</svg>
                    <div class="l-beta-input">
                        <input id="leadtime-customer-input"
                            class="c-beta-input c-beta-input--basic c-row-belongs-to__input"
                            placeholder="Link to a customer…" autocomplete="off">
                    </div>
                </span>
            </div>
		`;
        if (actionContainer) {
    	    actionContainer.prepend(customerField);
            const loader = document.getElementById('leadtime-customer-input-loader');
            const inputField = document.getElementById(customerFieldInputId);
            const getCustomerList = () => {
                const { value } = inputField;
                if (value === this.inputValue) {
                    return;
                }
                this.set('inputValue', value);
                removeCustomerList();
                if (this.customerId) {
                    this.set('customerId', '');
                    this.actions.fetchData();
                }
                if (!value) {
                    loader.style.visibility = 'hidden';
                    return;
                }
                if (timeoutId) {
                    clearTimeout(timeoutId);
                }
                loader.style.visibility = 'visible';
                timeoutId = setTimeout(value => {
                    this.get('store')
                        .query('forest-customer', { companyName: value })
                        .then(customers => {
                            addCustomerList(customers, this);
                        });
                    loader.style.visibility = 'hidden';
                }, 500, value);
            };
            inputField.addEventListener('keyup', getCustomerList);
            inputField.addEventListener('focus', () => {
                if (!this.customerId) {
                    this.set('inputValue', '');
                    getCustomerList();
                }
            });
            document.addEventListener('click', handleDocumentClick);
        }
        const globalElement = document.getElementById('global');
        if (customerField && globalElement && globalElement.classList.contains('v-editor')) {
            customerField.style.display = 'none';
        }
        if (editLayoutBtn) {
            editLayoutBtn.addEventListener('click', toggleCustomerField);
        }
        const searchBarInput = document.querySelector(`.${searchBarInputClass}`);
        const searchBarIcon = document.querySelector(`.${searchBarIconClass}`);
        if (searchBarInput) {
            searchBarInput.addEventListener('keydown', handleSearchBarInputKeydown);
            searchBarInput.addEventListener('input', handleSearchBarInputChange);
        }
        if (searchBarIcon) {
            searchBarIcon.addEventListener('click', handleSearchBarIconClick);
        }
    },
    didRender() {
        this.set('fetchRecords', this.actions.fetchData);
        const renderedFiltersButton = document.getElementById(filtersButtonId);
        if (renderedFiltersButton && renderedFiltersButton !== filtersButton) {
            filtersButton = renderedFiltersButton;
            filtersButton.addEventListener('click', handleFiltersButtonClick);
        }
        const renderedPaginationLeft = document.querySelector(paginationLeftQuery);
        if (renderedPaginationLeft && renderedPaginationLeft !== paginationLeft) {
            paginationLeft = renderedPaginationLeft;
            paginationLeft.addEventListener('click', event => {
                event.stopPropagation();
                if (component.currentPage === 1) {
                    return;
                }
                component.set('currentPage', component.currentPage - 1);
                component.actions.fetchData();
            });
        }
        const renderedPaginationRight = document.querySelector(paginationRightQuery);
        if (renderedPaginationRight && renderedPaginationRight !== paginationRight) {
            paginationRight = renderedPaginationRight;
            paginationRight.addEventListener('click', event => {
                event.stopPropagation();
                if (component.currentPage === component.numberOfPages) {
                    return;
                }
                component.set('currentPage', component.currentPage + 1);
                component.actions.fetchData();
            });
        }
        const renderedActionsButton = document.querySelector(actionsButtonQuery);
        if (renderedActionsButton && renderedActionsButton !== actionsButton) {
            actionsButton = renderedActionsButton;
            actionsButton.addEventListener('click', handleActionsButtonClick);
        }
    },
    willDestroyElement() {
        component = null;
        const filtersButtonText = document.querySelector(`.${filtersButtonTextClass}`);
        if (filtersButtonText) {
            filtersButtonText.textContent = 'Filter';
        }
        const customerField = document.getElementById(customerFieldId);
        if (customerField) {
            customerField.remove();
        }
        const editLayoutBtn = document.getElementById(editLayoutButtonId);
        if (editLayoutBtn) {
            editLayoutBtn.removeEventListener('click', toggleCustomerField);
        }
        document.removeEventListener('click', handleDocumentClick);
        const searchBarInput = document.querySelector(`.${searchBarInputClass}`);
        if (searchBarInput) {
            searchBarInput.removeEventListener('keydown', handleSearchBarInputKeydown);
            searchBarInput.removeEventListener('input', handleSearchBarInputChange);
        }
        const searchBarIcon = document.querySelector(`.${searchBarIconClass}`);
        if (searchBarIcon) {
            searchBarIcon.removeEventListener('click', handleSearchBarIconClick);
        }
        if (filtersButton) {
            filtersButton.removeEventListener('click', handleFiltersButtonClick);
            filtersButton = null;
        }
    },
    actions: {
        sortBy(column, order) {
            this.set('sortedField', column.get('field'));
            this.set('sortedField.order', 'asc' === order ? 'ascending' : 'descending');
            this.set('currentPage', 1);
            let sortQuery = column.get('field.field');
            const { field } = this.columnsVisible.find(({ field }) => field.field === sortQuery);
            if (field.hasReference) {
                sortQuery += `.${field.referenceDisplayField.field}`;
            }
            if (order === 'desc') {
                sortQuery = '-'.concat(sortQuery);
            }
            this.set('orderByNumber', 0);
            this.set('sortQuery', sortQuery);
            this.actions.fetchData();
        },
        fetchData() {
            const params = getParams();
            const countParams = {
                timezone: params.timezone,
            };
            if (params.filters) {
                countParams.filters = params.filters;
            }
            if (params.customerId) {
                countParams.customerId = params.customerId;
            }
            if (params.search) {
                countParams.search = params.search;
            }
            component.set('isLoading', true);
            component.get('store')
                .query('forest-lead', params)
                .then(leads => {
                    component.set('records', leads);
        	        component.set('isLoading', false);
                });
            component.get('store')
                .count(component.collection, countParams)
                .then(count => {
        	        component.set('recordsCount', count);
      	        });
        },
        exportLeads() {
            if (!component.records.content.length) {
                component.toastr.perform('error', 'There are no leads to export.');
                return;
            }
            const customActions = component.collection.get('customActionsOrdered');
            const exportAction = customActions.content.find(({ name }) => name === 'Export Leads');
            if (!exportAction || !exportAction.fieldsOrdered) {
                component.toastr.perform('error', 'Error occured. Can\'t export leads.');
                return;
            }
            const payload = {
                data: {
                    attributes: {
                        collection_name: 'leads',
                        values: {},
                        all_records: false,
                        all_records_subset_query: getParams(true),
                        smart_action_id: 'leads-Export@@@Leads',
                    },
                    type: 'custom-action-requests',
                },
            };
            const { fieldsOrdered } = exportAction;
            for (let i = 0; i < fieldsOrdered.length; i++) {
                const { isRequired, customActionValue, fieldName } = fieldsOrdered[i];
                if (isRequired && !customActionValue) {
                    component.toastr.perform('warning', `${fieldName} is required!`);
                    return;
                }
                if (customActionValue) {
                    payload.data.attributes.values[fieldName] = customActionValue;
                }
                if (fieldName === 'Export type' && customActionValue === 'Delivery' && !component.customerId) {
                    component.toastr.perform('warning', missingCustomerIdWarning);
                    return;
                }
            }
            component.set('isLoading', true);
            fetch(`${component.get('collection.rendering.environment.apiEndpoint')}${exportAction.endpoint}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${getCookieValue()}`,
                },
                body: JSON.stringify(payload),
            }).then(res => {
                if (res.status === 200) {
                    res.blob().then(blob => {
                        const href = window.URL.createObjectURL(blob);
                        const element = document.createElement('a');
                        element.style.display = 'none',
                        element.href = href;
                        element.download = 'leads.csv';
                        document.body.appendChild(element);
                        element.click();
                        window.URL.revokeObjectURL(href);
                        document.body.removeChild(element);
                        component.toastr.perform('success', 'Leads are successfully exported.');
                        component.actions.fetchData();
                    });
                } else {
                    res.json().then(({ error }) => {
                        component.set('isLoading', false);
                        component.toastr.perform('error', error || 'Could not export leads.');
                    });
                }
            }).catch(error => {
                component.set('isLoading', false);
                component.toastr.perform('error', error.message);
            });
        },
        getRandomLeads() {
            if (!component.records.content.length) {
                component.toastr.perform('error', 'There are no leads to randomize.');
                return;
            }
            const customActions = component.collection.get('customActionsOrdered');
            const exportAction = customActions.content.find(({ name }) => name === 'Get Random Leads');
            if (!exportAction) {
                component.toastr.perform('error', 'Error occured. Can\'t get random leads.');
                return;
            }
            const payload = {
                data: {
                    attributes: {
                        collection_name: 'leads',
                        all_records: false,
                        smart_action_id: 'leads-Get@@@Random@@@Leads',
                    },
                    type: 'custom-action-requests',
                },
            };
            component.set('isLoading', true);
            fetch(`${component.get('collection.rendering.environment.apiEndpoint')}${exportAction.endpoint}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${getCookieValue()}`,
                },
                body: JSON.stringify(payload),
            }).then(res => {
                if (res.status === 200) {
                    res.json().then(({ success }) => {
                        component.set('orderByNumber', Math.random());
                        component.toastr.perform('success', success);
                        component.actions.fetchData();
                    });
                } else {
                    res.json().then(({ error }) => {
                        component.set('isLoading', false);
                        component.toastr.perform('error', error || 'Could not export leads.');
                    });
                }
            }).catch(error => {
                component.set('isLoading', false);
                component.toastr.perform('error', error.message);
            });
        },
    },
});