var loader     = '<div id="loader" class="d-flex"><div class="spinner-border text-danger" role="status"><span class="visually-hidden">Loading...</span></div></div>';
var loaderSm   = '<div class="d-flex"><div class="spinner-border spinner-border-sm text-danger" role="status"><span class="visually-hidden">Loading...</span></div></div>';
var whLoader   = '<div class="d-flex"><div class="spinner-border spinner-border-sm text-light" role="status"><span class="visually-hidden">Loading...</span></div></div>';
var whLoaderLg = '<div class="d-flex"><div class="spinner-border text-light" role="status"><span class="visually-hidden">Loading...</span></div></div>';

function isValidUrl(url) {
    try { 
        return Boolean(new URL(url)); 
    } catch(e) { 
        return false; 
    }
}

var dzSelections = {
    init: function() {
        let selectionResultHtml = $('#automaticGroupsResult').html();

        this.on('addedfile', function(file, response) {
            $('#addPlans').hide();
            let ext = file.name.split('.').pop();
            if ( ext == 'pdf' || ext == 'PDF' ) {
                $(file.previewElement).find(".dz-details img").attr("src", "/clients/assets/images/pdf-icon.png").css('width', '120px').css('height', '120px');
            }
        });
        this.on("sending", function(file, xhr, formData) {
            $('#automaticGroupsResult').html(loader);
            $('#newGroupsSubmit').prop('disabled', true);
        });
        this.on('success', function(file, response) {
            // console.log(response);
            this.removeAllFiles();
            $('#addPlans').show();
            $('#automaticGroupsUploadArea').hide();
            $('#newGroupsSubmit').prop('disabled', false);
            $('#automaticGroupsResult').html(response);
        });
        this.on('error', function(file, message) {
            $('#newGroupsSubmit').prop('disabled', false);
            $('#automaticGroupsResult').html(selectionResultHtml);
        });
        this.on('reset', function() {
            $('#newGroupsSubmit').prop('disabled', false);
            $('#addPlans').show();
        });
    }, 
    url: "/clients/selections/ajax/new-groups-from-plan.php",
    // addRemoveLinks: true,
    autoProcessQueue: true,
    uploadMultiple: false,
    acceptedFiles: 'application/pdf',
    parallelUploads: 1,
    maxFilesize: 30,
    maxFiles: 1,
    previewTemplate: '<div class="dz-preview dz-file-preview text-center me-2"><div class="dz-details"><img data-dz-thumbnail /></div><div class="dz-filename"><span data-dz-name></span></div><div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div><div class="dz-error-message"><span data-dz-errormessage></span></div><a class="text-danger" href="javascript:undefined;" data-dz-remove>Remove</a></div>',
}

function initSelectionsDropzone() {
    return new Dropzone("div#selectionsDropzone", dzSelections);
}

var sdz = {
    init: function() {
        this.on('addedfile', function(file, response) {
            $('#uploadSelectionImage').hide();
        });
        this.on("sending", function(file, xhr, formData) {
            formData.append('title', $('#selectionItemTitle').val());
            formData.append('vendor', $('#selectionItemVendor').val());
            formData.append('description', $('#selectionItemDescription').val());
            formData.append('tags', $('#selectionItemTags').val());
            formData.append('unit', $('#selectionItemUnit').val());
            formData.append('cost', $('#selectionItemCost').val());
            formData.append('quantity', $('#selectionItemQuantity').val());
            formData.append('link', $('#selectionItemLink').val());
            // formData.append('selectionItemImageUrl', $('#selectionItemImageUrl').val());
            formData.append('projectId', $('#selectionItemProjectId').val());
            formData.append('groupId', $('#selectionItemGroupId').val());
            formData.append('fromdz', 1);
        });
        this.on('reset', function() {
            $('#uploadSelectionImage').show();
        });
        this.on('complete', function() {
            location.reload(true);
        });
    }, 
    url: "/clients/selections/src/new-selection-item.php",
    autoProcessQueue: false,
    uploadMultiple: false,
    acceptedFiles: 'image/jpeg,image/png',
    maxFilesize: 30,
    maxFiles: 1,
    previewTemplate: '<div class="dz-preview dz-file-preview text-center me-2"><div class="dz-details"><img data-dz-thumbnail /></div><div class="dz-filename"><span data-dz-name></span></div><div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div><div class="dz-error-message"><span data-dz-errormessage></span></div><a class="text-danger" href="javascript:undefined;" data-dz-remove>Remove</a></div>',
}

var esidz = {
    init: function() {
        this.on('addedfile', function(file, response) {
            $('#uploadEditSelectionItemImage').hide();
        });
        this.on("sending", function(file, xhr, formData) {
            formData.append('selectionItemId', $('#editSelectionItemId').val());
            formData.append('title', $('#editSelectionItemTitle').val());
            formData.append('vendor', $('#editSelectionItemVendor').val());
            formData.append('description', $('#editSelectionItemDescription').val());
            formData.append('unit', $('#editSelectionItemUnit').val());
            formData.append('cost', $('#editSelectionItemCost').val());
            formData.append('quantity', $('#editSelectionItemQuantity').val());
            formData.append('link', $('#editSelectionItemLink').val());
            formData.append('editSelectionItemFilename', $('#editSelectionItemFilename').val());
            formData.append('fromdz', 1);
        });
        this.on('reset', function() {
            $('#uploadEditSelectionItemImage').show();
        });
        this.on('complete', function() {
            location.reload(true);
        });
    }, 
    url: "/clients/selections/src/edit-selection-item.php",
    autoProcessQueue: false,
    uploadMultiple: false,
    acceptedFiles: 'image/jpeg,image/png',
    maxFilesize: 30,
    maxFiles: 1,
    previewTemplate: '<div class="dz-preview dz-file-preview text-center me-2"><div class="dz-details"><img data-dz-thumbnail /></div><div class="dz-filename"><span data-dz-name></span></div><div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div><div class="dz-error-message"><span data-dz-errormessage></span></div><a class="text-danger" href="javascript:undefined;" data-dz-remove>Remove</a></div>',
}

function initNewSelectionItemDropzone() {
    return new Dropzone("div#selectionItemDropzone", sdz);
}

function initEditSelectionItemDropzone() {
    return new Dropzone("div#editSelectionItemDropzone", esidz);
}

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

    $(document).on('click', '#selectionNewManualGroup', function(e) {
        let index = parseInt($('.selectionCheck').length) + 1;
        let html = '<div class="col-1"><div class="form-check"><input class="form-check-input selectionCheck" type="checkbox" name="selectionCheck['+index+']" value="" checked></div></div><div class="col-11"><input type="text" name="selectionText['+index+']" class="form-control selectionText mb-1" placeholder="Group name"></div>';
        $('#newManualGroupContainer').prepend(html);
        $('#newManualGroupContainer input[type="text"]').first().focus();
    });
    $(document).on('click', '#selectionNewAutomaticGroup', function(e) {
        let index = parseInt($('.selectionCheck').length) + 1;
        let html = '<div class="col-1"><div class="form-check"><input class="form-check-input selectionCheck" type="checkbox" name="selectionCheck['+index+']" value="" checked></div></div><div class="col-11"><input type="text" name="selectionText['+index+']" class="form-control selectionText mb-1" placeholder="Group name"></div>';
        $('#newAutomaticGroupContainer').prepend(html);
        $('#newAutomaticGroupContainer input[type="text"]').first().focus();
    });
    $(document).on('click', '#selectionAutomaticGroupReset', function(e) {
        $('#automaticGroupsResult').html('');
        $('#automaticGroupsUploadArea').show();
    });

    $(document).on('hide.bs.collapse', '.selectionGroupCollapse', function(e) {
        // $(this).parent().find('.card-header').addClass('rounded-bottom-4');
        $(this).parent().find('.selectionGroupCollapseToggle').html('<i class="bi bi-chevron-down"></i>');
    });
    $(document).on('show.bs.collapse', '.selectionGroupCollapse', function(e) {
        // $(this).parent().find('.card-header').removeClass('rounded-bottom-4');
        $(this).parent().find('.selectionGroupCollapseToggle').html('<i class="bi bi-chevron-up"></i>');
    });

    $(document).on('show.bs.dropdown', '.dropdownSelectionGroup', function() {
        // console.log($(this));
        // console.log($(this).closest('.card').find('.collapse'));
        $(this).closest('.card').find('.collapse').addClass('show');
        $(this).closest('.card').find('.selectionGroupCollapseToggle').html('<i class="bi bi-chevron-up"></i>');
    });

    $(document).on('click', '.newSelectionItemButton', function(e) {
        let groupId = $(this).data('group');
        $('#selectionItemGroupId').val(groupId);
    });

    $(document).on('click', '#newAutomaticSelectionItemButton', function(e) {
        let url = $('#newAutomaticSelectionItemUrl').val();
        if ( !isValidUrl(url) ) {
            console.log('invalid url');
            return;
        }

        $('#newAutomaticSelectionItemUrl').prop('disabled', true);
        $('#newAutomaticSelectionItemButton').prop('disabled', true);
        $('#resetNewSelectionItemFormButton').prop('disabled', true);
        $('#saveNewSelectionItemButton').prop('disabled', true);
        $('#newAutomaticSelectionItemButton').html(whLoader);

        $.ajax({
            url: '/clients/selections/ajax/new-automatic-selection-item.php',
            method: 'POST',
            data: {
                url: url
            },
            success: function(data) {
                // toastr["success"]("Plan deleted", "Success");
                let response = JSON.parse(data);

                $('#selectionItemTitle').val(response.title);
                $('#selectionItemVendor').val(response.vendor);
                $('#selectionItemDescription').val(response.description);
                $('#selectionItemCost').val(response.cost);
                $('#selectionItemUnit').val(response.unit);
                $('#selectionItemLink').val(response.link);
                $('#selectionItemImageUrl').val(response.selectionItemImageUrl);

                sidz.removeAllFiles();
                $('#selectionItemDropzoneContainer').addClass('d-none');

                $('#newAutomaticSelectionItemImage').attr('src', response.selectionItemImageUrl);
                $('#newAutomaticSelectionItemImageContainer').removeClass('d-none');

                $('#newAutomaticSelectionItemUrl').prop('disabled', false);
                $('#newAutomaticSelectionItemButton').html('Go <i class="bi bi-magic"></i>');
                $('#newAutomaticSelectionItemButton').prop('disabled', false);
                $('#resetNewSelectionItemFormButton').prop('disabled', false);
                $('#saveNewSelectionItemButton').prop('disabled', false);

                const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]')
                const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))
            },
            error: function(e) {
                // toastr["error"](message, "Error");

                $('#newAutomaticSelectionItemUrl').prop('disabled', false);
                $('#newAutomaticSelectionItemButton').html('Go <i class="bi bi-magic"></i>');
                $('#newAutomaticSelectionItemButton').prop('disabled', false);
                $('#resetNewSelectionItemFormButton').prop('disabled', false);
                $('#saveNewSelectionItemButton').prop('disabled', false);
            },
        });
    });

    $(document).on('click', '#resetNewSelectionItemFormButton', function(e) {
        $('#selectionItemTitle').val('');
        $('#selectionItemVendor').val('');
        $('#selectionItemDescription').val('');
        $('#selectionItemUnit').val('');
        $('#selectionItemCost').val('');
        $('#selectionItemQuantity').val('');
        $('#selectionItemLink').val('');
        $('#selectionItemImageUrl').val('');

        $('#newAutomaticSelectionItemImage').attr('src', '');
        $('#newAutomaticSelectionItemImageContainer').addClass('d-none');

        sidz.removeAllFiles();
    });

    $(document).on('submit', '#newSelectionItemForm', function(e) {
        $('#saveNewSelectionItemButton').prop('disabled', true);
        $('#newSelectionItemModalFooter').html(loader);
        if ( sidz.files.length > 0 ) {
            e.preventDefault();
            e.stopPropagation();
            sidz.processQueue();
        } else {
            $('#newSelectionItemForm').submit();
        }
    });

    $(document).on('click', '#removeSelectionItemImageButton', function(e) {
        $('#selectionItemImageUrl').val('');
        $('#newAutomaticSelectionItemImageContainer').addClass('d-none');
        $('#selectionItemDropzoneContainer').removeClass('d-none');
    });

    $(document).on('click', '.editSelectionGroupButton', function(e) {
        $('#editGroupModalBody').html(loader);

        let groupId = $(this).data('group');

        $.ajax({
            url: '/clients/selections/ajax/edit-group-form.php',
            method: 'POST',
            dataType: 'html',
            data: {
                groupId: groupId
            },
            success: function (data) {
                // console.log(data);
                $('#editGroupModalBody').html(data);
            },
            error: function (e) {
                // var error = e.responseJSON.error;
                // console.log(error);
            }
        });
    });

    $(document).on('click', '.editSelectionItemButton', function(e) {
        $('#editSelectionItemWrapper').addClass('d-none');
        $('#editSelectionItemModalBody').append(loader);

        let selectionItemId = $(this).data('id');

        $.ajax({
            url: '/clients/selections/ajax/edit-selection-item-form.php',
            method: 'POST',
            dataType: 'html',
            data: {
                selectionItemId: selectionItemId
            },
            success: function (data) {
                // console.log(data);
                let response = JSON.parse(data);
                // console.log(response);

                $('#loader').remove();
                $('#editSelectionItemWrapper').removeClass('d-none');
                $('#editSelectionItemImageContainer').removeClass('d-none');
                $('#editSelectionItemDropzoneContainer').addClass('d-none');


                if ( response.image ) {
                    $('#editSelectionItemImage').attr('src', '/clients/selections/assets/attachments/'+response.image);
                } else {
                    $('#editSelectionItemImageContainer').addClass('d-none');
                    $('#editSelectionItemDropzoneContainer').removeClass('d-none');
                }

                $('#editSelectionItemId').val(response.id);
                $('#editSelectionItemFilename').val(response.image);
                $('#editSelectionItemTitle').val(response.title);
                $('#editSelectionItemVendor').val(response.vendor);
                $('#editSelectionItemDescription').val(response.description);
                $('#editSelectionItemUnit').val(response.unit);
                $('#editSelectionItemCost').val(response.cost);
                $('#editSelectionItemQuantity').val(response.quantity);
                $('#editSelectionItemLink').val(response.link);
                if ( !response.link ) {
                    $('#editSelectionItemLinkButton').hide();
                } else {
                    $('#editSelectionItemLinkButton').attr('href', response.link);
                    $('#editSelectionItemLinkButton').show();
                }
                if ( $('#deleteSelectionItemButton').length ) {
                    $('#deleteSelectionItemButton').attr('href', '/clients/selections/src/delete-selection-item.php?itemId='+response.id);
                }

                let array = [];
                for ( let i = 0; i < response.tags.length; i++ ) {
                    array.push(response.tags[i].tagId.toString());
                    // console.log(response.tags[i]);
                    // console.log(response.tags[i].tagId);
                }

                $('#editSelectionItemTags').selectpicker('val', array);

                const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]')
                const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))
            },
            error: function (e) {
                // var error = e.responseJSON.error;
                // console.log(error);
            }
        });
    });

    $(document).on('click', '#removeEditSelectionItemImageButton', function(e) {
        $('#editSelectionItemFilename').val('');
        $('#editSelectionItemImageContainer').addClass('d-none');
        $('#editSelectionItemDropzoneContainer').removeClass('d-none');
    });

    $(document).on('submit', '#editSelectionItemForm', function(e) {
        $('#saveEditSelectionItemButton').prop('disabled', true);
        $('#editSelectionItemModalFooter').html(loader);
        if ( editSelectionItemDz.files.length > 0 ) {
            e.preventDefault();
            e.stopPropagation();
            editSelectionItemDz.processQueue();
        } else {
            $('#editSelectionItemForm').submit();
        }
    });
    
    $(document).on('click', '.viewSelectionGroupFinishScheduleButton', function(e) {
        let groupId = $(this).data('group');
        $('.groupCheck').each(function() {
            if ( $(this).val() != groupId ) {
                $(this).prop('checked', false);
            }
        });
        $('#groupCheck-'+groupId).prop('checked', true);
    });

    $(document).on('change', '.selectionItemCheck', function(e) {
        let groupId = $(this).data('group-id');
        $('.selectionItemCheck-group-'+groupId).each(function(i, e) {
            if ( $(this).is(':checked') ) {
                console.log($(this));
            }
        });
    });

    Sortable.create(document.getElementById('selectionGroupContainer'), {
        delay: 100,
        delayOnTouchOnly: true,
        handle: '.selectionGroupHandle',
        onEnd: function(evt) {
            let order = [];
            $('.selectionGroup').each(function(i, e) {
                order.push({"id": $(e).data('id'), "order": i});
            });
            console.log(order);

            $.ajax({
                url: '/clients/selections/ajax/order-selection-groups.php',
                method: 'POST',
                data: {
                    id: $('#projectId').val(),
                    order: order
                },
                success: function(data) {
                    // console.log(data);
                },
                error: function (e) {
                }
            });
        },
    });

    $('.selectionItemsList').each(function() {
        let groupId = $(this).data('id');
        Sortable.create(document.getElementById('selection-group-'+groupId), {
            delay: 100,
            delayOnTouchOnly: true,
            handle: '.selectionItemHandle',
            onStart: function(evt) {
                $('.selectionItem-'+groupId).addClass('shrink');
            },
            onEnd: function(evt) {
                let order = [];
                $('.selectionItem-'+groupId).each(function(i, e) {
                    order.push({"id": $(e).data('id'), "order": i});
                });
                console.log(order);

                $.ajax({
                    url: '/clients/selections/ajax/order-selection-items.php',
                    method: 'POST',
                    data: {
                        id: $('#projectId').val(),
                        order: order
                    },
                    success: function(data) {
                        // console.log(data);
                    },
                    error: function (e) {
                    }
                });
            },
        });
    });

    Fancybox.bind("[data-fancybox]", {
        Toolbar: {
            display: {
                left: ["infobar"],
                middle: [],
                right: ["iterateZoom", "slideshow", "thumbs", "download", "close"],
            },
        },
    });
    
    initObserver();
    $('.selectpicker').selectpicker();

    const selectionsDz = initSelectionsDropzone();
    const sidz = initNewSelectionItemDropzone();
    const editSelectionItemDz = initEditSelectionItemDropzone();
});