var ScheduledEmailReportsFormView = Backbone.View.extend({
    autocompleteUrl: {
        'employee': 'get-employees-by-search-term',
        'customer': 'get-customers-by-search-term',
    },
    events: {
        'change #sendEvery': 'showReportOptions',
        'change #reportName': 'showReportOptions',
        'click .remove-email-icon': 'removeEmail',
        'click #addEmailBtn': 'addEmail',
        'keyup #employee, #customer': 'autocomplete',
        'keyup input.validate': 'validateForm',


    },
    initialize: function (options) {
        this.options = options;
        this.template = _.template(options.template);
        // this.model = options.model;
        this.scheduledReport = options.scheduledReport;
        this.reportKeys = Object.keys(options.reports);
        this.reports = options.reports;
    },

    render: function () {
        var that = this;
        this.$el.detach();
        this.$el.html(this.template({
            scheduledReport: this.scheduledReport,
            reportKeys: this.reportKeys,
            reports: this.reports,
        }));

        $(document).ready(function () {
            $('.tooltipped').tooltip();
            // var timepickerElement = document.querySelector('.timepicker');
            // var timepicker = M.Timepicker.init(timepickerElement, {
            //     onSelect: () => {
            //         timepicker.close();
            //     },
            //     onCloseEnd: () => {
            //         timepickerElement.value = timepicker.hours + ":00 " + timepicker.amOrPm
            //     },
            //     container: 'body',
            //     i18n: App.i18n
            // });

            var datepickerElement = document.querySelector('#startDate');
            var datepicker = M.Datepicker.init(datepickerElement, {
                autoClose: true,
                container: 'body',
                i18n: App.i18n,
                format: 'yyyy-mm-dd'
            });

            $('select').formSelect();
            that.showReportOptions();
            that.initAutocomplete();

        });

        return this;
    },

    showReportOptions: function () {
        var selectedSendEvery = document.getElementById('sendEvery').value;
        if (selectedSendEvery.includes('Day')) {
            $('.dayOfWeek').hide();
            $('.dayOfMonth').hide();
        } else if (selectedSendEvery.includes('Week')) {
            $('.dayOfMonth').hide();
            $('.dayOfWeek').show();
        } else if (selectedSendEvery.includes('Month')) {
            $('.dayOfWeek').hide();
            $('.dayOfMonth').show();
        }

        var options = document.querySelectorAll('.option');
        for (option of options) {
            option.style.display = 'none';
        }

        try {
            var selectedReport = document.getElementById('reportName').value;
            var reportOptions = this.reports[selectedReport].options;
            reportOptions.forEach(option => {
            document.querySelector(`div[data-option="${option}"]`).style.display = 'block';
        })
        } catch (error) {
            console.log(selectedReport);
        }
        

        if(selectedReport == 'z_reset_summary'){
            $('.sendEvery').hide();
            $('.dayOfWeek').hide();
            $('.dayOfMonth').hide();
        }
        else
            $('.sendEvery').show();

    },

    removeEmail: function (e) {
        e.currentTarget.parentElement.parentElement.remove();
    },

    addEmail: function () {
        document.getElementById('emailsList').insertAdjacentHTML('beforeend',
            `<div class="col m3 s12">
        <div class="input-field row">
            <i class="material-icons small prefix remove-email-icon red-text" style="cursor: pointer;">close</i>
            <input class="email validate" type="email" value="">
            <span class="helper-text" data-error="wrong" data-success="">{Literal}incorrect email format{/Literal}</span>
        </div>
        </div>`);
    },
    initAutocomplete: function () {
        var that = this;
        var baseOptions = {
            minLength: 1,
            limit: 20,
            sortFunction: function (a, b, inputString) {
                return a.indexOf(inputString) - b.indexOf(inputString);
            }
        };
        // var employeeOptions = _.extend({
        //     onAutocomplete: function (selection) { that.employeeSearchAutocompleteSelection = selection; } 
        // }, baseOptions);
        M.Autocomplete.init(document.querySelector('#customer'), _.extend({
            onAutocomplete: function (selection) {
                document.querySelector('#customer').value = selection.split(' / ')[0];
            }
        }, baseOptions));
        M.Autocomplete.init(document.querySelector('#employee'), baseOptions);
    },
    autocomplete: function (e) {
        var element = e.currentTarget;
        var searchTerm = element.value;
        var that = this;
        if (searchTerm.trim().length > 0) {
            if (this.timer) {
                clearTimeout(this.timer);
            }
            this.timer = setTimeout(function () {
                that.getBySearchTerm(searchTerm, element);
            }, 300);
        }
    },
    getBySearchTerm: function (searchTerm, element) {
        var that = this;
        var url = this.autocompleteUrl[element.id];
        var sessionToken = getCookie();
        $.ajax({
            url: '/data/' + url,
            data: {
                searchTerm: searchTerm,
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                var results = data.results;
                var items = {};
                if (element.id == 'employee') {
                    for (var i = 0; i < results.length; i++) {
                        items[results[i].value] = null;
                    }
                } else if (element.id == 'customer') {
                    for (var i = 0; i < results.length; i++) {
                        items[results[i].id + ' / ' + results[i].name + ' / ' + results[i].phone] = null;
                    }
                }
                var autocomplete = element.M_Autocomplete;
                autocomplete.updateData(items);
                autocomplete.open();
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
            }
        });
    },
});