(function($) {
    "use strict";

    let uploadBox = $('.uploadbox'),
        uploadBoxBtn = $('[data-upload-btn]'),
        dragBox = $('.dz-dragbox');
    if (uploadBox.length) {

        let uploadConfigObjects = JSON.stringify(uploadConfig),
            getUploadConfig = JSON.parse(uploadConfigObjects);

        uploadBoxBtn.on('click', function() {
            uploadBox.addClass('active');
            $('body').addClass("overflow-hidden");
        });

        uploadBox.find('.btn-close').on('click', function() {
            if (dropzone.getQueuedFiles().length > 0 || dropzone.getUploadingFiles().length > 0) {
                let removeConfirm = confirm(getUploadConfig.closeUploadBoxAlert);
                if (removeConfirm) {
                    dropzone.removeAllFiles(true);
                    uploadBox.removeClass("active");
                    $('body').removeClass("overflow-hidden");
                }
            } else {
                dropzone.removeAllFiles(true);
                uploadBox.removeClass("active");
                $('body').removeClass("overflow-hidden");
            }
        });

        let UploadUrl = getConfig.baseURL + '/upload';
        let previewNode = document.querySelector('#upload-previews');
        previewNode.id = "";
        let previewTemplate = previewNode.innerHTML;
        previewNode.parentNode.removeChild(previewNode);

        var dropzoneMakeConfig = {
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: UploadUrl,
                method: 'POST',
                paramName: 'file',
                filesizeBase: 1024,
                maxFiles: parseInt(getUploadConfig.maxUploadFiles),
                acceptedFiles: getUploadConfig.types.accepted,
                previewTemplate: previewTemplate,
                previewsContainer: "#dropzone",
                autoProcessQueue: false,
                clickable: "[data-dz-click]",
                parallelUploads: parseInt(getUploadConfig.maxUploadFiles),
                timeout: 0,
                chunking: true,
                forceChunking: true,
                chunkSize: parseInt(getUploadConfig.chunkSize),
                retryChunks: true,
            },
            dropzoneConfig = Object.assign({}, dropzoneMakeConfig, dropzoneOptions);

        Dropzone.autoDiscover = false;
        var dropzone = new Dropzone("#dropzone-wrapper", dropzoneConfig);


        let uploadMoreBtn = $('.upload-more-btn'),
            uploadboxWrapperForm = $('.uploadbox-wrapper-form'),
            submitBtn = $(".upload-files-btn"),
            uploadAutoDelete = $('.upload-auto-delete');
        submitBtn.on('click', function(e) {
            e.preventDefault();
            if (dropzone.files.length > 0) {
                if (getUploadConfig.filesDuration != "") {
                    let action = uploadAutoDelete.find(':selected').data('action');
                    if (action > getUploadConfig.filesDuration) {
                        toastr.error(getUploadConfig.filesDurationError);
                    } else {
                        submitBtn.prop('disabled', true);
                        uploadboxWrapperForm.addClass('d-none');
                        uploadMoreBtn.addClass('d-none');
                        dropzone.processQueue();
                    }
                } else {
                    submitBtn.prop('disabled', true);
                    uploadboxWrapperForm.addClass('d-none');
                    uploadMoreBtn.addClass('d-none');
                    dropzone.processQueue();
                }
            } else {
                toastr.error(getUploadConfig.nofilesAttachedError);
            }
        });

        let resetUploadBox = $('.reset-upload-box');
        resetUploadBox.on('click', function() {
            dropzone.removeAllFiles(true);
        });

        function uploadBoxDrag() {
            let uploadboxDrag = $('.uploadbox-drag'),
                uploadboxWrapper = $('.uploadbox-wrapper');
            if (dropzone.files.length > 0) {
                uploadboxDrag.addClass("inactive");
                uploadboxWrapper.addClass("active");
                $('body').addClass("overflow-hidden");
                resetUploadBox.removeClass("d-none");
                uploadBox.addClass("active");
                uploadMoreBtn.removeClass('show');
            } else {
                uploadboxDrag.removeClass("inactive");
                uploadboxWrapper.removeClass("active");
                resetUploadBox.addClass("d-none");
                submitBtn.prop('disabled', false);
                uploadboxWrapperForm.removeClass('d-none');
                uploadMoreBtn.removeClass('show');
            }
        }

        function onAddFile(file) {
            if (dropzone.files.length <= getUploadConfig.maxUploadFiles) {
                if (file.type === "video/mp4" || file.type === "video/webm") {
                    if (this.files.length) {
                        var _i, _len;
                        for (_i = 0, _len = this.files.length; _i < _len - 1; _i++) {
                            if (this.files[_i].name === file.name) {
                                this.removeFile(file);
                                toastr.error(getUploadConfig.fileDuplicateError);
                            }
                        }
                    }
                    if (file.size == 0) {
                        toastr.error(getUploadConfig.emptyFilesError);
                        this.removeFile(file);
                    }
                    if (getUploadConfig.maxFileSize != "") {
                        if (file.size > getUploadConfig.maxFileSize) {
                            toastr.error(getUploadConfig.exceedTheAllowedSizeError);
                            this.removeFile(file);
                        }
                    }
                    if (getUploadConfig.clientReminingSpace != "") {
                        if (file.size > getUploadConfig.clientReminingSpace) {
                            toastr.error(getUploadConfig.clientReminingSpaceError);
                            this.removeFile(file);
                        }
                    }
                    uploadBoxDrag();
                    if (dropzone.files.length == getUploadConfig.maxUploadFiles) {
                        uploadMoreBtn.addClass('d-none');
                    }
                    let preview = $(file.previewElement),
                        fileSize = preview.find('.dz-size'),
                        fileEdit = preview.find('.dz-file-edit'),
                        fileEditBtn = preview.find("[data-dz-edit]"),
                        fileEditBtnIcon = preview.find(".dz-edit .fas"),
                        fileEditCLose = preview.find(".dz-file-edit-close"),
                        fileEditSubmit = preview.find(".dz-file-edit-submit"),
                        editPasswordInput = preview.find('.file-password'),
                        fileIcon = $('[data-dz-icon]');;
                    if (file.type === "video/mp4") {
                        fileIcon.prop('src', getUploadConfig.types.icons.mp4);
                    } else if (file.type === "video/webm") {
                        fileIcon.prop('src', getUploadConfig.types.icons.webm);
                    }
                    fileSize.html(formatBytes(file.size));
                    editPasswordInput.on('input', function() {
                        editPasswordInput.removeClass('is-invalid');
                    });
                    fileEditBtn.on('click', function() {
                        if (editPasswordInput.val() != "") {
                            editPasswordInput.attr('fill-status', true);
                        }
                        editPasswordInput.prop('disabled', false);
                        fileEdit.addClass("active");
                    });
                    fileEditCLose.on('click', function() {
                        if (editPasswordInput.val() == "") {
                            editPasswordInput.prop('disabled', true);
                            editPasswordInput.attr('fill-status', false);
                            fileEditBtnIcon.removeClass('fa-lock');
                            fileEditBtnIcon.addClass('fa-lock-open');
                        } else {
                            if (editPasswordInput.attr('fill-status') == "false") {
                                editPasswordInput.val("");
                                editPasswordInput.prop('disabled', true);
                                fileEditBtnIcon.removeClass('fa-lock');
                                fileEditBtnIcon.addClass('fa-lock-open');
                            }
                        }
                        editPasswordInput.removeClass('is-invalid');
                        fileEdit.removeClass("active");
                    });
                    fileEditSubmit.on('click', function() {
                        if (editPasswordInput.val() == "") {
                            editPasswordInput.addClass('is-invalid');
                        } else {
                            fileEditBtnIcon.addClass('fa-lock');
                            fileEditBtnIcon.removeClass('fa-lock-open');
                            fileEdit.removeClass("active");
                        }
                    });
                } else {
                    this.removeFile(file);
                    toastr.error(getUploadConfig.unacceptableFileTypesError);
                }
            } else {
                this.removeFile(file);
            }
        }

        function onSending(file, xhr, formData) {
            let preview = $(file.previewElement),
                fileRemoveBtn = preview.find('.dz-remove'),
                editDetailsIcon = preview.find('.dz-edit'),
                password = preview.find('.file-password');
            formData.append('size', file.size);
            formData.append('type', file.type);
            if (password.length) {
                formData.append('password', password.val());
            }
            formData.append('upload_auto_delete', $('.upload-auto-delete').val());
            fileRemoveBtn.remove();
            editDetailsIcon.remove();
        }


        function onUploadProgress(file, progress) {
            let preview = $(file.previewElement);
            preview.find(".dz-upload-precent").html(progress.toFixed(0) + "%");
        }

        function onFileError(file, message = null) {
            toastr.error(message);
        }

        function onUploadComplete(file) {
            if (file.status == "success") {
                let preview = $(file.previewElement),
                    response = JSON.parse(file.xhr.response);
                if (response.type == 'success') {
                    let previewContainer = preview.find('.dz-preview-container');
                    previewContainer.append('<div class="mt-3"><label class="form-label">' + getUploadConfig.translation.shareLink + '</label><div class="form-button"><input id="' + response.file_id + '" type="text" class="form-control form-control-md" value="' + response.file_link + '" readonly /><button class="btn-copy" data-clipboard-target="#' + response.file_id + '"><i class="fa-regular fa-clone"></i></button></div></div><div class="mt-3"><a href="' + response.file_link + '" target="_blank" class="btn btn-primary btn-md w-100"><i class="fa-solid fa-up-right-from-square me-2"></i>' + getUploadConfig.translation.openLink + '</a></div>');
                    clipboardJS();
                } else {
                    preview.removeClass('dz-success');
                    preview.addClass('dz-error');
                    toastr.error(response.msg);
                }
            }
        }

        function onRemovedfile() {
            uploadBoxDrag();
        }

        function onDragover() {
            dragBox.addClass("show");
        }

        function onDragleave() {
            dragBox.removeClass("show");
        }

        function formatBytes(bytes, decimals = 2) {
            if (bytes === 0) return "0 " + getUploadConfig.translation.formatSizes[0];
            const k = 1024;
            const dm = decimals < 0 ? 0 : decimals;
            const sizes = getUploadConfig.translation.formatSizes;
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
        }

        function clipboardJS() {
            let uploadedFileClipboardBtn = document.querySelectorAll(".btn-copy");
            if (uploadedFileClipboardBtn) {
                uploadedFileClipboardBtn.forEach((el) => {
                    let uploadedFileClipboard = new ClipboardJS(el);
                    uploadedFileClipboard.on("success", () => {
                        toastr.success(getConfig.copiedToClipboardSuccess);
                    });
                });
            }
        }

        dropzone.on("addedfile", onAddFile);
        dropzone.on('sending', onSending);
        dropzone.on("removedfile", onRemovedfile);
        dropzone.on('uploadprogress', onUploadProgress);
        dropzone.on('error', onFileError);
        dropzone.on('complete', onUploadComplete);
        dropzone.on('dragover', onDragover);
        dropzone.on('dragleave', onDragleave);
        dropzone.on('drop', onDragleave);
    }
})(jQuery);