jQuery(document).ready(function ($) {
    

    var planner = $('.keyword-planner');

    var editGroupBox = planner.find('#edit-group-box');
    var editKeywordsBox = planner.find('#edit-keywords-box');
    var editKeywordBox = planner.find('#edit-keyword-box');

    var groups = {};

    var init = function () {
        init_tooltips();
        
        groups = {};

        planner.find('#group-table-body .group-row').each(function (key, row) {
            var groupData = $.parseJSON($(row).attr('init'));
            groups[groupData.id] = groupData;
        });
    };
    
    var init_tooltips = function(){
        $("[data-toggle=tooltip]").tooltip();
    };

    var update_groups_selector = function (id) {
        var selector = editKeywordsBox.find('#group-selector');
        selector.html('');

        for (var key in groups) {
            var option = $('<option/>');
            option.val(key);
            option.text(groups[key].name);

            if (id && id == key) { // select default group
                option.attr('selected', 'selected');
            }

            selector.append(option);
        }
    };

    var add_group_handler = function () {
        editGroupBox.find('input').val('');
        if (editGroupBox.hasClass('hide')) {
            hide_boxes();
            editGroupBox.removeClass('hide')
        } else {
            editGroupBox.addClass('hide')
        }
        hide_errors();
    };

    var add_keywords_handler = function () {
        hide_errors();

        editKeywordsBox.find('textarea').val('');

        if (editKeywordsBox.hasClass('hide')) {
            hide_boxes();
            editKeywordsBox.removeClass('hide')
        } else {
            editKeywordsBox.addClass('hide')
        }

        if ($(this).is('.group-add-keywords-btn')) {
            var id = $(this).closest('.group-row').data('id');
            update_groups_selector(id);
        } else {
            update_groups_selector();
        }

    };

    var edit_group_handler = function () {
        hide_errors();
        hide_boxes();

        var groupId = $(this).closest('.group-row').attr('data-id');

        editGroupBox.find('#field-edit-group-name').val(groups[groupId].name)
        editGroupBox.find('#field-group-id').val(groupId)

        editGroupBox.removeClass('hide');
    };

    var edit_group_discard_handler = function () {
        hide_boxes();
    };

    var edit_group_save_handler = function () {
        var id = editGroupBox.find('#field-group-id').val();
        $.post(ajaxurl, {
            action: 'dashnex-planner-group-save',
            name: editGroupBox.find('#field-edit-group-name').val(),
            id: id
        }, function (data) {
            if (data.success == false) {
                show_group_error(data.message);
            } else {
                group_update(data.group);
                toggle_buttons();

                hide_boxes();
            }
        }, 'json');
    };

    var groupId;
    var group_delete_modal_handler = function () {
        groupId = $(this).closest('.group-row').attr('data-id');
        planner.find('#delete-group-modal').modal('show')
    };

    var group_delete_handler = function () {
        delete_group(groupId);
    };

    var keywordId;
    var keyword_delete_modal_handler = function () {
        keywordId = $(this).closest('.keyword-row').data('id');
        planner.find('#delete-keyword-modal').modal('show')
    };

    var keyword_delete_handler = function () {
        delete_keyword(keywordId);
    };

    var delete_keyword = function (id) {
        $.post(ajaxurl, {
            action: 'dashnex-planner-keyword-delete',
            id: id
        }, function (data) {
            if (data.success == true) {
                var $keywordRow = planner.find('.keyword-row[data-id=' + id + ']');
                var groupId = $keywordRow.closest('.group-row').data('id');

                $keywordRow.remove();
                delete groups[groupId].keywords[id];
            }
        }, 'json')
    };

    var edit_keyword_handler = function(e) {
        hide_boxes();
        hide_errors();

        var groupId = $(this).closest('.group-row').data('id');
        var keywordId = $(this).closest('.keyword-row').data('id');

        var keyword = groups[groupId].keywords[keywordId];

        editKeywordBox.find('#field-edit-keyword-id').val(keyword.id);
        editKeywordBox.find('#field-edit-keyword-name').val(keyword.name);
        editKeywordBox.find('#field-edit-keyword-cost').val(keyword.costPerClick);
        editKeywordBox.find('#field-edit-keyword-volume').val(keyword.trafficVolume);

        editKeywordBox.removeClass('hide');
    };

    var edit_keyword_discard_handler = function () {
        hide_boxes();
        hide_errors();
    };

    var edit_keyword_save_handler = function(){
        hide_errors();

        $.post(ajaxurl, {
            action: 'dashnex-planner-keyword-save',
            id: editKeywordBox.find('#field-edit-keyword-id').val(),
            name: editKeywordBox.find('#field-edit-keyword-name').val(),
            costPerClick: editKeywordBox.find('#field-edit-keyword-cost').val(),
            trafficVolume: editKeywordBox.find('#field-edit-keyword-volume').val()
        }, function (data) {
            if (data.success == false) {
                show_keyword_error(data.message);
            } else {
                keyword_update(data.keyword);
                hide_boxes();
            }

        }, 'json')
    };

    var delete_group = function (id) {
        $.post(ajaxurl, {
            action: 'dashnex-planner-group-delete',
            id: id
        }, function (data) {
            if (data.success == true) {
                planner.find('.group-row[data-id=' + id + ']').remove();
                delete groups[id];

                toggle_buttons();
                hide_boxes();
            }
        }, 'json')
    };

    var edit_keywords_discard_handler = function () {
        editKeywordsBox.addClass('hide')
    };

    var edit_keywords_save_handler = function () {
        $.post(ajaxurl, {
            action: 'dashnex-planner-keywords-save',
            keywords: editKeywordsBox.find('#field-edit-keywords-value').val(),
            groupId: editKeywordsBox.find('#group-selector').val()
        }, function (data) {
            if (data.success == false) {
                show_keywords_error(data.message);
            } else {
                group_update(data.group);
                toggle_buttons();
                editKeywordsBox.addClass('hide');
            }

        }, 'json')
    };

    var toggle_buttons = function() {
        if (Object.keys(groups).length > 0 ) {
            planner.find('#add-keywords-btn, #export-modal-btn, #delete-all-btn').removeClass('hide');
        } else {
            planner.find('#add-keywords-btn, #export-modal-btn, #delete-all-btn').addClass('hide');
        }
    };

    var group_add = function (group) {
        var groupRow = $('#group-row').clone();
        groupRow.attr('data-id', group.id);
        groupRow.find('.group-name').text(group.name);

        planner.find('#group-table-body').append(groupRow);

        return groupRow;
    };

    var group_update = function (group) {
        var groupRow = planner.find('.group-row[data-id=' + group.id + ']');

        if (groupRow.length == 0) {
            groupRow = group_add(group);
        }

        groupRow.find('.group-name').text(group.name);
        groupRow.find('.group-competition-strength').text(group.competitionStrength || '');

        groups[group.id] = group;

        groupRow.find('.keyword-row').remove();

        $.each(group.keywords, function (id, keyword) {
            var $keywordRow = $('#keyword-row').clone();
            $keywordRow.find('.keyword-name').text(keyword.name);
            $keywordRow.find('.keyword-cost').text(keyword.costPerClick);
            $keywordRow.find('.keyword-volume').text(keyword.trafficVolume);
            $keywordRow.find('.keyword-competition-strength').text(keyword.competitionStrength || '');
            $keywordRow.attr('data-id', id);
            groupRow.find('.keywords').append($keywordRow)
        });

        init_tooltips();
    };

    var keyword_update = function(keyword) {

        groups[keyword.groupId].keywords[keyword.id] = keyword;

        var $keywordRow = planner.find('.keyword-row[data-id='+keyword.id+']');

        $keywordRow.find('.keyword-name').text(keyword.name);
        $keywordRow.find('.keyword-cost').text(keyword.costPerClick);
        $keywordRow.find('.keyword-volume').text(keyword.trafficVolume);
        $keywordRow.find('.keyword-competition-strength').text(keyword.competitionStrength || '');
    };

    var show_group_error = function (text) {
        planner.find('#error-message-group-edit').text(text).removeClass('hide')
    };

    var show_keywords_error = function (text) {
        planner.find('#error-message-keywords-edit').text(text).removeClass('hide')
    };

    var show_keyword_error = function (text) {
        planner.find('#error-message-keyword-edit').text(text).removeClass('hide')
    };

    var show_import_export_error = function (text) {
        planner.find('#error-message-import-export').text(text).removeClass('hide')
    };

    var show_success_message = function (text) {
        planner.find('#success_message').text(text).removeClass('hide')
    };

    var show_progress_message = function () {
        planner.find('#progress-message').removeClass('hide');
    };

    var hide_progress_message = function () {
        planner.find('#progress-message').addClass('hide');
    };

    var hide_errors = function () {
        planner.find('.error').text('').addClass('hide');
        planner.find('#success_message').text('').addClass('hide');
    };

    var hide_boxes = function () {
        editGroupBox.addClass('hide');
        editKeywordsBox.addClass('hide')
        editKeywordBox.addClass('hide')
    };

    var export_all_modal_handler = function () {
        hide_errors();
        hide_boxes();

        planner.find('#export-all-modal').modal('show');
    };

    var importCsv = function () {

        var btn = $(this).closest('.btn');
        var source = planner.find('#import-source');
        var form = planner.find('#import-form');
        var loading = form.find('.loading');

        source.off('load');
        btn.addClass('disabled');
        loading.removeClass('hide');
        hide_errors();
        hide_boxes();
        show_progress_message();

        source.on('load', function () {
            source.off('load');
            loading.addClass('hide');
            btn.removeClass('disabled');
            planner.find('#dashnex_adwords_csv').val('');

            var data = $.parseJSON(source.contents().find('body').text());

            hide_progress_message();

            if (typeof data.success != 'undefined' && data.success === false) {
                show_import_export_error(data.message);
            } else {
                show_success_message(data.message);
                $.each(data.groups, function (id, group) {
                    group_update(group);
                });
                toggle_buttons();
            }
        });

        form.attr('action', ajaxurl);
        form.submit();
    };

    var delete_all_modal_handler = function(){
        hide_errors();
        planner.find('#delete-all-modal').modal('show');
    };

    var delete_all_handler = function () {
        hide_errors();
        delete_all();
    };

    var delete_all = function() {
        $.post(ajaxurl, {
            action: 'dashnex-planner-all-delete'
        }, function (data) {

            if (data.success && data.success == true) {
                groups = [];
                planner.find('#group-table-body .group-row').remove();
            }
            toggle_buttons();
        }, 'json')
    };

    var group_export_modal_handler = function () {
        hide_errors();
        groupId = $(this).closest('.group-row').data('id');
        planner.find('#group-export-modal').modal('show')
    };

    var group_export_handler = function () {
        $.post(ajaxurl, {
            action: 'dashnex-planner-group-export',
            groupId: groupId
        }, function (data) {
            if (data.success == false) {
                show_import_export_error(data.message)

                $.each(data.result.keywordsToDelete, function (id) {
                    delete_keyword(id)
                });
            } else {
                show_success_message(data.message);
                group_delete_handler();
            }
            update_category_keywords_list();
        }, 'json')
    };

    var keyword_export_modal_handler = function () {
        hide_errors();
        keywordId = $(this).closest('.keyword-row').data('id');

        var modal = planner.find('#keyword-export-modal');

        modal.find('.categories').val('');
        modal.find('#keyword-export-btn').addClass('disabled');
        modal.find('.variant').removeClass('active');
        modal.modal('show');
    };

    var exportVariant;
    var exportCategoryId;

    var keyword_export_handler = function (e) {
        e.preventDefault();

        $.post(ajaxurl, {
            action: 'dashnex-planner-keyword-export',
            keywordId: keywordId,
            variant: exportVariant,
            categoryId: exportCategoryId
        }, function (data) {
            if (typeof data.success != 'undefined' && data.success === false) {
                show_import_export_error(data.message)
            } else {
                show_success_message(data.message);

                keyword_delete_handler();

                if (exportVariant == 'category') {
                    update_category_keywords_list();
                }
            }
        }, 'json')
    };

    var variant_select_handler = function (e) {
        e.preventDefault();

        var thisModal = planner.find('#keyword-export-modal');

        thisModal.find('#keyword-export-btn').addClass('disabled');
        $(this).siblings().removeClass('active');
        $(this).addClass('active');

        exportVariant = $(this).data('variant');

        if (exportVariant == 'keyword') {
            exportCategoryId = $(this).find('.categories').val();

            if (exportCategoryId !== null && exportCategoryId !== '') {
                thisModal.find('#keyword-export-btn').removeClass('disabled');
            }
        } else if (exportVariant == 'category'){
            thisModal.find('#keyword-export-btn').removeClass('disabled');
        }


    };

    var update_category_keywords_list = function () {
        $.post(ajaxurl, {
            action: 'dashnex-planner-get-categories'
        }, function (response) {
            var container = planner.find('.categories');
            container.html('<option></option>');

            $.each(response.categoryKeywords, function (key, category) {
                var option = $('<option/>')
                    .attr('value', category.id)
                    .text(category.keyword);

                container.append(option);
            })
        }, 'json')
    };

    var export_all_handler = function () {
        planner.find('.exporting').removeClass('hide');
        planner.find('#export-modal-btn').addClass('disabled')

        $.post(ajaxurl, {
            'action': 'dashnex-planner-export-all'
        }, function (data) {

            if (data.success == true) {
                show_success_message(data.message);
                delete_all();
            } else {
                show_import_export_error(data.message);

                $.each(data.result, function (gid, group) {

                    if (typeof group.keywordsExist.length != 'undefined') {
                        delete_group(gid)
                    } else if (Object.keys(group.keywordsToDelete).length > 0) {

                        $.each(group.keywordsToDelete, function (kid, keyword) {
                            delete_keyword(kid)
                        })
                    }
                })

            }
            planner.find('.exporting').addClass('hide')
            planner.find('#export-modal-btn').removeClass('disabled')
        }, 'json')
    };

    var help_modal_handler = function(e){
        e.preventDefault();
        planner.find('#dashnex-keyword-planner-modal').modal('show');
    };

    var keyword_get_competition_strength_handler = function() {

        var $element = $(this);
        var $loadingIcon = $element.siblings('.loading');

        $([$element, $loadingIcon]).toggleClass('hide');

        $.post(ajaxurl, {
            action: 'dashnex-planner-get-competition-strength-for-keyword',
            keyword: {
                id : $(this).closest('.keyword-row').data('id')
            }
        }, function (data) {
            if (data.success == false) {
                show_keyword_error(data.message);
            } else {
                keyword_update(data.keyword);
            }

            $([$element, $loadingIcon]).toggleClass('hide');
        }, 'json')
    };

    var group_get_competition_strength_handler = function() {

        var $element = $(this);
        var $loadingIcon = $element.siblings('.loading');

        $([$element, $loadingIcon]).toggleClass('hide');

        $.post(ajaxurl, {
            action: 'dashnex-planner-get-competition-strength-for-group',
            group: {
                id : $(this).closest('.group-row').data('id')
            }
        }, function (data) {
            if (data.success == false) {
                show_keyword_error(data.message);
            } else {
                group_update(data.group);
            }

            $([$element, $loadingIcon]).toggleClass('hide');

        }, 'json')
    };


    init();

    planner.find('#add-group-btn').on('click', add_group_handler);
    planner.find('#edit-group-discard-btn').on('click', edit_group_discard_handler);
    planner.find('#edit-group-save-btn').on('click', edit_group_save_handler);
    planner.find('#confirm-group-delete-btn').on('click', group_delete_handler);
    planner.find('#group-export-btn').on('click', group_export_handler);

    planner.on('click', '.group-delete-modal-btn', group_delete_modal_handler);
    planner.on('click', '.group-edit-btn', edit_group_handler);
    planner.on('click', '.group-add-keywords-btn', add_keywords_handler);
    planner.on('click', '.group-export-modal-btn', group_export_modal_handler);
    planner.on('click', '.group-get-competition-strength', group_get_competition_strength_handler);

    planner.find('#edit-keywords-discard-btn').on('click', edit_keywords_discard_handler);
    planner.find('#edit-keyword-discard-btn').on('click', edit_keyword_discard_handler);
    planner.find('#edit-keyword-save-btn').on('click', edit_keyword_save_handler);
    planner.find('#edit-keywords-save-btn').on('click', edit_keywords_save_handler);
    planner.find('#add-keywords-btn').on('click', add_keywords_handler);
    planner.find('#confirm-keyword-delete-btn').on('click', keyword_delete_handler);
    planner.find('#keyword-export-btn').on('click', keyword_export_handler);

    planner.on('click', '.keyword-delete-modal-btn', keyword_delete_modal_handler);
    planner.on('click', '.keyword-export-modal-btn', keyword_export_modal_handler);
    planner.on('click', '.keyword-edit', edit_keyword_handler);
    planner.on('click', '.keyword-get-competition-strength', keyword_get_competition_strength_handler);

    planner.find('#export-modal-btn').on('click', export_all_modal_handler);

    planner.find('#confirm-delete-all-btn').on('click', delete_all_handler);
    planner.find('#delete-all-btn').on('click', delete_all_modal_handler);
    planner.find('#export-all-btn').on('click', export_all_handler);

    planner.find('textarea, input').on('keyup', hide_errors);
    planner.find('#dashnex_adwords_csv').on('change', importCsv);

    planner.find('.variant').on('click', variant_select_handler);
    planner.find('#show-keyword-planner-modal-btn').on('click', help_modal_handler)
});