//jQuery code 
jQuery(document).ready(function ($) {
    // Toggle MIME type status - Auto-save when toggling
    $(document).on('change', '.checkbox', function () {
        var $checkbox = $(this);
        var extension = $checkbox.val();
        var isChecked = $checkbox.is(':checked');

        // Get all current MIME types
        var mimes = [];
        $('.checkbox:checked').each(function () {
            mimes.push($(this).val());
        });

        // Save immediately
        saveSettings(mimes);
    });

    // Delete MIME type
    $(document).on('click', '.delete-mime', function (e) {
        e.preventDefault();
        var extension = $(this).data('extension');
        var $row = $(this).closest('tr');

        Swal.fire({
            title: "Are you sure?",
            text: "You won't be able to revert this!",
            icon: "warning",
            security: uamt.nonce,
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Yes, delete it!"
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: uamt.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'uamt_delete_mime',
                        security: uamt.nonce,
                        extension: extension
                    },
                    beforeSend: function () {
                        $row.css('opacity', '0.5');
                    },
                    success: function (response) {
                        if (response.success) {
                            // Remove the row from UI
                            $row.fadeOut(300, function () {
                                $(this).remove();
                            });

                            Swal.fire({
                                title: "Deleted!",
                                text: "MIME type has been deleted.",
                                icon: "success",
                                toast: true,
                                position: "top-end",
                                showConfirmButton: false,
                                timer: 3000,
                                timerProgressBar: true,
                                customClass: {
                                    container: 'uamt-swal-container',
                                }
                            });
                        } else {
                            $row.css('opacity', '1');
                            Swal.fire({
                                title: "Error!",
                                text: response.data.message || "Failed to delete MIME type",
                                icon: "error",
                                toast: true,
                                position: "top-end",
                                showConfirmButton: false,
                                timer: 3000,
                                timerProgressBar: true,
                                customClass: {
                                    container: 'uamt-swal-container',
                                }
                            });
                        }
                    },
                    error: function () {
                        $row.css('opacity', '1');
                        Swal.fire({
                            title: "Error!",
                            text: "An error occurred while deleting the MIME type",
                            icon: "error",
                            toast: true,
                            position: "top-end",
                            showConfirmButton: false,
                            timer: 3000,
                            timerProgressBar: true,
                            customClass: {
                                container: 'uamt-swal-container',
                            }
                        });
                    }
                });
            }
        });
    });

    // Add custom MIME type to the main table when clicking +
    $(document).on('click', '.add-row', function (e) {
        e.preventDefault();

        // Get the current row's input values
        var $row = $(this).closest('.mime-row');
        var desc = $row.find('input[name*="[desc]"]').val().trim();
        var mime = $row.find('input[name*="[mime]"]').val().trim();
        var ext = $row.find('input[name*="[ext]"]').val().trim();

        // Validate inputs
        if (!desc || !mime || !ext) {
            Swal.fire({
                title: "Error!",
                text: "Please fill all fields",
                icon: "error",
                toast: true,
                position: "top-end",
                showConfirmButton: false,
                timer: 3000,
                timerProgressBar: true,
                customClass: {
                    container: 'uamt-swal-container',
                }
            });
            return;
        }

        // Validate MIME type format
        if (!/^[a-z]+\/[a-z0-9\-\.\+]+$/i.test(mime)) {
            Swal.fire({
                title: "Error!",
                text: "Please enter a valid MIME type (e.g., application/pdf)",
                icon: "error",
                toast: true,
                position: "top-end",
                showConfirmButton: false,
                timer: 3000,
                timerProgressBar: true,
                customClass: {
                    container: 'uamt-swal-container',
                }
            });

            $row.find('input[name*="[mime]"]').css('border', '1px solid red');
            return;
        } else {
            $row.find('input[name*="[mime]"]').css('border', '');
        }

        // Check if extension already exists
        var extensionExists = false;
        $('.checkbox').each(function () {
            if ($(this).val() === ext) {
                extensionExists = true;
                return false; // break loop
            }
        });

        if (extensionExists) {
            Swal.fire({
                title: "Warning!",
                text: "This file extension already exists",
                icon: "warning",
                toast: true,
                position: "top-end",
                showConfirmButton: false,
                timer: 3000,
                timerProgressBar: true,
                customClass: {
                    container: 'uamt-swal-container',
                }
            });
            return;
        }

        // Create new row in main table
        var $newRow = $(`
            <tr>
                <td>
                    <label class="switch">
                        <input type="checkbox" checked id="toggle-${ext}" class="checkbox" name="uamt_mimes[]" value="${ext}">
                        <span class="slider"></span>
                    </label>
                </td>
                <td>${desc}</td>
                <td>${mime}</td>
                <td>.${ext}</td>
                <td>
                    <a href="#" class="button button-small delete-mime" 
                    data-extension="${ext}" 
                    title="Delete this MIME type">
                        <span class="dashicons dashicons-trash"></span>
                    </a>
                </td>
            </tr>
        `);

        // Add to top of table
        $('.uamt_table').prepend($newRow);

        // Clear the input fields
        $row.find('input').val('');

        // Prepare data for saving
        var mimes = [];
        $('.checkbox:checked').each(function () {
            mimes.push($(this).val());
        });

        var customMimes = {
            desc: [desc],
            mime: [mime],
            ext: [ext]
        };

        // Save automatically
        saveSettings(mimes, customMimes);
    });

    // Remove MIME type row
    $(document).on('click', '.remove-row', function () {
        if ($('.mime-row').length > 1) {
            $(this).closest('.mime-row').remove();
        } else {
            $(this).closest('.mime-row').find('input').val('');
        }
    });

    // Toggle custom section
    $('#toggle-custom-section').click(function (e) {
        e.preventDefault();
        $('.ua-custom-section').toggle();
    });

    // File drag and drop
    var $dropArea = $('#mime-drop-area');

    $dropArea.on('dragover', function (e) {
        e.preventDefault();
        $dropArea.addClass('dragover');
    });

    $dropArea.on('dragleave', function (e) {
        e.preventDefault();
        $dropArea.removeClass('dragover');
    });

    $dropArea.on('drop', function (e) {
        e.preventDefault();
        $dropArea.removeClass('dragover');

        var files = e.originalEvent.dataTransfer.files;
        if (files.length > 0) {
            processFiles(files);
        }
    });

    $('#select-files-btn').click(function () {
        $('#mimeFileInput').click();
    });

    $('#mimeFileInput').change(function () {
        if (this.files.length > 0) {
            processFiles(this.files);
        }
    });

    // Process dropped/selected files
    function processFiles(files) {
        const file = files[0];
        if (!file) return;

        const fileSizeMB = file.size / (1024 * 1024); // Convert bytes to MB
        const estimatedSeconds = Math.ceil(fileSizeMB * 1.5);
        const estimatedTimeMs = estimatedSeconds * 1000;

        let timerInterval;

        // Start Swal loader with timer based on MB
        Swal.fire({
            title: 'Uploading file...',
            html: `Please wait. Time left: <b>${estimatedSeconds}</b> seconds`,
            allowOutsideClick: false,
            showConfirmButton: false,
            showCloseButton: false,
            toast: false,
            timer: estimatedTimeMs,
            timerProgressBar: true,
            customClass: {
                container: 'uamt-swal-container-uploading',
            },
            didOpen: () => {
                Swal.showLoading();
                const b = Swal.getHtmlContainer().querySelector('b');
                timerInterval = setInterval(() => {
                    if (b) {
                        const secondsLeft = Math.ceil(Swal.getTimerLeft() / 1000);
                        b.textContent = secondsLeft;
                    }
                }, 100);
            },
            willClose: () => {
                clearInterval(timerInterval);
            }
        });

        const formData = new FormData();
        formData.append('action', 'uamt_upload_mime');
        formData.append('security', uamt.nonce);
        formData.append('file', file);

        // AJAX request
        $.ajax({
            url: uamt.ajax_url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                Swal.close();
                if (response.success) {
                    const data = response.data;

                    // Check if extension already exists
                    let extensionExists = false;
                    $('.checkbox').each(function () {
                        if ($(this).val() === data.ext) {
                            extensionExists = true;
                            return false;
                        }
                    });

                    if (extensionExists) {
                        Swal.fire({
                            title: "Warning!",
                            text: "This file extension already exists.",
                            icon: "warning",
                            toast: true,
                            position: "top-end",
                            showConfirmButton: false,
                            timer: 3000,
                            timerProgressBar: true,
                            customClass: {
                                container: 'uamt-swal-container',
                            }
                        });
                        return;
                    }

                    // Add new MIME row
                    const $newRow = $(`
                    <tr>
                        <td>
                            <label class="switch">
                                <input type="checkbox" checked id="toggle-${data.ext}" class="checkbox" name="uamt_mimes[]" value="${data.ext}">
                                <span class="slider"></span>
                            </label>
                        </td>
                        <td>${data.name}</td>
                        <td>${data.mime}</td>
                        <td>.${data.ext}</td>
                        <td>
                            <a href="#" class="button button-small delete-mime" data-extension="${data.ext}" title="Delete this MIME type">
                                <span class="dashicons dashicons-trash"></span>
                            </a>
                        </td>
                    </tr>`);

                    $('.ua-table-container table tbody.uamt_table').prepend($newRow);

                    Swal.fire({
                        title: "Success!",
                        text: "MIME type added successfully.",
                        icon: "success",
                        toast: true,
                        position: "top-end",
                        showConfirmButton: false,
                        timer: 3000,
                        timerProgressBar: true,
                        customClass: {
                            container: 'uamt-swal-container',
                        }
                    });

                    // Scroll and save
                    $('html, body').animate({
                        scrollTop: $('.ua-table-container').offset().top
                    }, 1000);

                    const mimes = [];
                    $('.checkbox:checked').each(function () {
                        mimes.push($(this).val());
                    });

                    const customMimes = {
                        desc: [data.name],
                        mime: [data.mime],
                        ext: [data.ext]
                    };

                    saveSettings(mimes, customMimes);
                } else {
                    // Swal.fire({
                    //     title: "Error!",
                    //     text: response.data?.message || "Failed to process file safsfsf",
                    //     icon: "error",
                    //     toast: true,
                    //     position: "top-end",
                    //     showConfirmButton: false,
                    //     timer: 3000
                    // });
                    Swal.fire({
                        title: "Warning!",
                        text: "This file extension already exists.",
                        icon: "warning",
                        toast: true,
                        position: "top-end",
                        showConfirmButton: false,
                        timer: 3000,
                        timerProgressBar: true,
                        customClass: {
                            container: 'uamt-swal-container',
                        }
                    });
                }
            },
            error: function (xhr) {
                Swal.close();
                let message = 'Error processing file';
                try {
                    const response = JSON.parse(xhr.responseText);
                    message = response.data?.message || message;
                } catch (e) { }

                Swal.fire({
                    title: "Error!",
                    text: message,
                    icon: "error",
                    toast: true,
                    position: "top-end",
                    showConfirmButton: false,
                    timer: 3000
                });
            }
        });
    }

    // Save button handler
    $('form').on('submit', function (e) {
        e.preventDefault();

        // Get all MIME types
        var mimes = [];
        $('.checkbox:checked').each(function () {
            mimes.push($(this).val());
        });

        // Get custom MIME data
        var customMimes = {
            desc: [],
            mime: [],
            ext: []
        };

        $('.mime-row').each(function () {
            var desc = $(this).find('input[name*="[desc]"]').val();
            var mime = $(this).find('input[name*="[mime]"]').val();
            var ext = $(this).find('input[name*="[ext]"]').val();

            if (desc && mime && ext) {
                customMimes.desc.push(desc);
                customMimes.mime.push(mime);
                customMimes.ext.push(ext);
            }
        });

        // Save settings
        saveSettings(mimes, customMimes);
    });

    // Save settings function
    function saveSettings(mimes, customMimes) {
        var data = {
            action: 'uamt_save_settings',
            security: uamt.save_nonce,
            uamt_mimes: mimes || [],
            uamt_save_settings: '1'
        };

        if (customMimes) {
            data.custom_mimes = customMimes;
        }

        $.ajax({
            url: uamt.ajax_url,
            type: 'POST',
            data: data,
            beforeSend: function () {
                $('.uamt-button-primary').prop('disabled', true)
                    .find('.dashicons').removeClass('dashicons-yes').addClass('dashicons-update spin');
            },
            success: function (response) {
                if (response.success) {
                    Swal.fire({
                        title: "Success!",
                        text: "Settings saved successfully.",
                        icon: "success",
                        toast: true,
                        position: "top-end",
                        showConfirmButton: false,
                        timer: 3000,
                        timerProgressBar: true,
                        customClass: {
                            container: 'uamt-swal-container',
                        }
                    });
                } else {
                    Swal.fire({
                        title: "Error!",
                        text: response.data?.message || "Failed to save settings",
                        icon: "error",
                        toast: true,
                        position: "top-end",
                        showConfirmButton: false,
                        timer: 3000,
                        timerProgressBar: true,
                        customClass: {
                            container: 'uamt-swal-container',
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
                var message = '';
                try {
                    var response = JSON.parse(xhr.responseText);
                    message = response.data?.message || error;
                } catch (e) {
                    message = error;
                }
                Swal.fire({
                    title: "Error!",
                    text: message || "An error occurred while saving settings",
                    icon: "error",
                    toast: true,
                    position: "top-end",
                    showConfirmButton: false,
                    timer: 3000,
                    timerProgressBar: true,
                    customClass: {
                        container: 'uamt-swal-container',
                    }
                });
            },
            complete: function () {
                $('.uamt-button-primary').prop('disabled', false)
                    .find('.dashicons').removeClass('dashicons-update spin').addClass('dashicons-yes');
            }
        });
    }

    // Debounced search functionality
    var searchTimeout;
    $('#ua-search-input').on('keyup', function () {
        clearTimeout(searchTimeout);
        var $input = $(this);

        searchTimeout = setTimeout(function () {
            var value = $input.val().toLowerCase();
            $('.uamt_table tr').each(function () {
                var $row = $(this);
                if ($row.text().toLowerCase().indexOf(value) > -1) {
                    $row.show();
                } else {
                    $row.hide();
                }
            });
        }, 300);
    });

    // Reset settings handler
    $(document).on('click', '#uamt-reset-settings', function (e) {
        e.preventDefault();

        Swal.fire({
            title: "Are you sure?",
            text: "This will reset all MIME type settings to their default values. This action cannot be undone.",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#d33",
            cancelButtonColor: "#3085d6",
            cancelButtonText: "Cancel",
            confirmButtonText: "Reset"
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: uamt.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'uamt_reset_settings',
                        security: uamt.nonce
                    },
                    beforeSend: function () {
                        $('#uamt-reset-settings').prop('disabled', true)
                            .find('.dashicons').removeClass('dashicons-update').addClass('dashicons-update spin');
                    },
                    success: function (response) {
                        if (response.success) {
                            Swal.fire({
                                title: "Success!",
                                text: "Settings reset successfully.",
                                icon: "success",
                                toast: true,
                                position: "top-end",
                                showConfirmButton: false,
                                timer: 3000,
                                timerProgressBar: true,
                                customClass: {
                                    container: 'uamt-swal-container',
                                }
                            });
                            setTimeout(function () {
                                location.reload();
                            }, 3000);
                        } else {
                            Swal.fire({
                                title: "Error!",
                                text: response.data?.message || "Failed to reset settings",
                                icon: "error",
                                toast: true,
                                position: "top-end",
                                showConfirmButton: false,
                                timer: 3000,
                                timerProgressBar: true,
                                customClass: {
                                    container: 'uamt-swal-container',
                                }
                            });
                        }
                    },
                    error: function (xhr) {
                        var message = 'Error resetting settings';
                        try {
                            var response = JSON.parse(xhr.responseText);
                            message = response.data?.message || message;
                        } catch (e) { }

                        Swal.fire({
                            title: "Error!",
                            text: message,
                            icon: "error",
                            toast: true,
                            position: "top-end",
                            showConfirmButton: false,
                            timer: 3000,
                            timerProgressBar: true,
                            customClass: {
                                container: 'uamt-swal-container',
                            }
                        });
                    },
                    complete: function () {
                        $('#uamt-reset-settings').prop('disabled', false)
                            .find('.dashicons').removeClass('dashicons-update spin').addClass('dashicons-update');
                    }
                });
            }
        });
    });

});