/**
 * Password Reset JavaScript
 * Handles client-side password generation, strength checking, and form submission
 */

function initPasswordResetForm() {
    // Generate secure password
    $('#generate-password-btn').on('click', function () {
        var password = generateSecurePassword();
        $('#temporary-password-input').val(password);
        checkPasswordStrength(password);

        // Show the password briefly
        $('#temporary-password-input').attr('type', 'text');
        setTimeout(function () {
            $('#temporary-password-input').attr('type', 'password');
        }, 3000);
    });

    // Toggle password visibility
    $('#toggle-password-visibility').on('click', function () {
        var input = $('#temporary-password-input');
        var icon = $('#toggle-icon');
        var btn = $(this);
        var trans = window.passwordResetTranslations || {};

        if (input.attr('type') === 'password') {
            input.attr('type', 'text');
            icon.removeClass('mdi-eye').addClass('mdi-eye-off');
            btn.html('<i class="mdi mdi-eye-off" id="toggle-icon"></i> ' + (trans.hidePassword || 'Hide Password'));
        } else {
            input.attr('type', 'password');
            icon.removeClass('mdi-eye-off').addClass('mdi-eye');
            btn.html('<i class="mdi mdi-eye" id="toggle-icon"></i> ' + (trans.showPassword || 'Show Password'));
        }
    });

    // Check password strength on input
    $('#temporary-password-input').on('input', function () {
        var password = $(this).val();
        if (password.length > 0) {
            checkPasswordStrength(password);
        } else {
            $('#password-strength-indicator').hide();
        }
    });

    // Handle form submission
    $('#reset-password-form').on('submit', function (e) {
        e.preventDefault();

        var form = $(this);
        var submitBtn = $('#submit-reset-btn');
        var originalText = submitBtn.html();
        var trans = window.passwordResetTranslations || {};

        // Disable submit button
        submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> ' + (trans.processing || 'Processing...'));

        $.ajax({
            url: form.attr('action'),
            type: 'POST',
            data: form.serialize(),
            dataType: 'json',
            success: function (response) {
                if (response.success) {
                    // Show success modal with temporary password
                    showSuccessModal(response.temporary_password, response.target_username, response.target_email);
                } else {
                    // Show error message in modal
                    displayFormErrors(response);
                    submitBtn.prop('disabled', false).html(originalText);
                }
            },
            error: function (xhr, status, error) {
                var trans = window.passwordResetTranslations || {};
                displayFormErrors({
                    message: trans.errorOccurred || 'An error occurred while processing your request.',
                    errors: { '': [(trans.serverError || 'Server error: ') + error] }
                });
                submitBtn.prop('disabled', false).html(originalText);
            }
        });
    });
}

/**
 * Displays form validation errors in the modal
 * @param {object} response - Server response with errors
 */
function displayFormErrors(response) {
    var errorContainer = $('#reset-password-errors');
    var errorMessages = $('#reset-password-error-messages');
    var trans = window.passwordResetTranslations || {};

    // Clear previous errors
    errorMessages.empty();

    // Build error message HTML
    var errorHtml = '<p>' + (response.message || trans.correctErrors || 'Please correct the following errors:') + '</p>';

    if (response.errors && Object.keys(response.errors).length > 0) {
        errorHtml += '<ul class="mb-0">';
        $.each(response.errors, function(field, messages) {
            if (Array.isArray(messages)) {
                $.each(messages, function(index, message) {
                    errorHtml += '<li>' + message + '</li>';
                });
            } else {
                errorHtml += '<li>' + messages + '</li>';
            }
        });
        errorHtml += '</ul>';
    }

    errorMessages.html(errorHtml);
    errorContainer.show();

    // Scroll to error
    errorContainer[0].scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

/**
 * Generates a secure random password
 * @returns {string}
 */
function generateSecurePassword() {
    var uppercase = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
    var lowercase = 'abcdefghjkmnpqrstuvwxyz';
    var numbers = '23456789';
    var special = '!@#$%^&*()-_=+';

    var password = '';

    // Ensure at least one of each required character type
    password += uppercase.charAt(Math.floor(Math.random() * uppercase.length));
    password += lowercase.charAt(Math.floor(Math.random() * lowercase.length));
    password += numbers.charAt(Math.floor(Math.random() * numbers.length));
    password += special.charAt(Math.floor(Math.random() * special.length));

    // Fill the rest randomly
    var allChars = uppercase + lowercase + numbers + special;
    for (var i = 0; i < 8; i++) {
        password += allChars.charAt(Math.floor(Math.random() * allChars.length));
    }

    // Shuffle the password
    password = password.split('').sort(function () {
        return 0.5 - Math.random();
    }).join('');

    return password;
}

/**
 * Checks password strength and updates UI
 * @param {string} password
 */
function checkPasswordStrength(password) {
    var strength = 0;
    var feedback = [];
    var trans = window.passwordResetTranslations || {};

    // Check length
    if (password.length >= 7) {
        strength += 20;
    } else {
        feedback.push(trans.minCharacters || 'Min 7 characters');
    }

    // Check for uppercase
    if (/[A-Z]/.test(password)) {
        strength += 20;
    } else {
        feedback.push(trans.oneUppercase || '1 uppercase');
    }

    // Check for lowercase
    if (/[a-z]/.test(password)) {
        strength += 20;
    } else {
        feedback.push(trans.oneLowercase || '1 lowercase');
    }

    // Check for numbers
    if (/\d/.test(password)) {
        strength += 20;
    } else {
        feedback.push(trans.oneDigit || '1 digit');
    }

    // Check for special characters
    if (/[\W_]/.test(password)) {
        strength += 20;
    } else {
        feedback.push(trans.oneSpecialChar || '1 special char');
    }

    // Update UI
    var strengthBar = $('#password-strength-bar');
    var strengthText = $('#password-strength-text');
    var strengthIndicator = $('#password-strength-indicator');

    strengthIndicator.show();
    strengthBar.css('width', strength + '%');

    if (strength === 100) {
        strengthBar.removeClass().addClass('progress-bar bg-success');
        strengthText.text(trans.strongPassword || 'Strong password').removeClass().addClass('form-text text-success');
    } else if (strength >= 60) {
        strengthBar.removeClass().addClass('progress-bar bg-warning');
        strengthText.text((trans.weakPassword || 'Weak: ') + feedback.join(', ')).removeClass().addClass('form-text text-warning');
    } else {
        strengthBar.removeClass().addClass('progress-bar bg-danger');
        strengthText.text((trans.tooWeak || 'Too weak: ') + feedback.join(', ')).removeClass().addClass('form-text text-danger');
    }
}

/**
 * Shows the success modal with temporary password
 * @param {string} password
 * @param {string} username
 * @param {string} email
 */
function showSuccessModal(password, username, email) {
    // Close current modal
    $('.modal').modal('hide');

    var trans = window.passwordResetTranslations || {};

    // Create success modal HTML
    var modalHtml = `
        <div class="modal fade" id="password-reset-success-modal" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-md" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">${trans.passwordResetSuccessful || 'Password Reset Successful'}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-success" role="alert">
                            <p>${(trans.tempPasswordSet || 'The temporary password for <strong>{username}</strong> has been set.').replace('{username}', username)}</p>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">${trans.temporaryPassword || 'Temporary Password'}</label>
                            <div class="input-group">
                                <input type="password" id="success-temp-password" class="form-control" value="${password}" readonly>
                                <button type="button" class="btn btn-outline-secondary" id="success-toggle-visibility">
                                    <i class="mdi mdi-eye"></i>
                                </button>
                                <button type="button" class="btn btn-primary" id="success-copy-password">
                                    <i class="mdi mdi-content-copy"></i> ${trans.copy || 'Copy'}
                                </button>
                            </div>
                            <small class="form-text text-muted">
                                ${(trans.shareSecurely || 'Share this password securely with {username} ({email}).').replace('{username}', username).replace('{email}', email)}
                            </small>
                        </div>

                        <div class="alert alert-info" role="alert">
                            ${trans.requiredToChange || 'The user will be required to change their password on next login.'}
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" data-bs-dismiss="modal" id="success-close-btn">${trans.close || 'Close'}</button>
                    </div>
                </div>
            </div>
        </div>
    `;

    // Remove existing success modal if any
    $('#password-reset-success-modal').remove();

    // Append and show new modal
    $('body').append(modalHtml);
    var successModal = new bootstrap.Modal(document.getElementById('password-reset-success-modal'));
    successModal.show();

    // Bind events
    $('#success-toggle-visibility').on('click', function () {
        var input = $('#success-temp-password');
        var icon = $(this).find('i');

        if (input.attr('type') === 'password') {
            input.attr('type', 'text');
            icon.removeClass('mdi-eye').addClass('mdi-eye-off');
        } else {
            input.attr('type', 'password');
            icon.removeClass('mdi-eye-off').addClass('mdi-eye');
        }
    });

    $('#success-copy-password').on('click', function () {
        var button = $(this);
        var trans = window.passwordResetTranslations || {};

        // Use modern Clipboard API if available, fallback to old method
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(password).then(function() {
                // Success
                button.html('<i class="mdi mdi-check"></i> ' + (trans.copied || 'Copied!')).removeClass('btn-primary').addClass('btn-success');

                setTimeout(function () {
                    button.html('<i class="mdi mdi-content-copy"></i> ' + (trans.copy || 'Copy')).removeClass('btn-success').addClass('btn-primary');
                }, 2000);
            }).catch(function(err) {
                // Fallback if clipboard API fails
                console.error('Clipboard API failed:', err);
                copyToClipboardFallback(password, button);
            });
        } else {
            // Fallback for older browsers
            copyToClipboardFallback(password, button);
        }
    });

    // Fallback copy function
    function copyToClipboardFallback(text, button) {
        var trans = window.passwordResetTranslations || {};
        var tempInput = $('<textarea>');
        tempInput.css({
            position: 'fixed',
            opacity: 0,
            top: 0,
            left: 0
        });
        $('body').append(tempInput);
        tempInput.val(text);
        tempInput[0].select();
        tempInput[0].setSelectionRange(0, 99999); // For mobile devices

        try {
            var successful = document.execCommand('copy');
            if (successful) {
                button.html('<i class="mdi mdi-check"></i> ' + (trans.copied || 'Copied!')).removeClass('btn-primary').addClass('btn-success');

                setTimeout(function () {
                    button.html('<i class="mdi mdi-content-copy"></i> ' + (trans.copy || 'Copy')).removeClass('btn-success').addClass('btn-primary');
                }, 2000);
            } else {
                button.html('<i class="mdi mdi-alert"></i> ' + (trans.failed || 'Failed')).removeClass('btn-primary').addClass('btn-danger');
                setTimeout(function () {
                    button.html('<i class="mdi mdi-content-copy"></i> ' + (trans.copy || 'Copy')).removeClass('btn-danger').addClass('btn-primary');
                }, 2000);
            }
        } catch (err) {
            console.error('Fallback copy failed:', err);
            button.html('<i class="mdi mdi-alert"></i> ' + (trans.failed || 'Failed')).removeClass('btn-primary').addClass('btn-danger');
            setTimeout(function () {
                button.html('<i class="mdi mdi-content-copy"></i> ' + (trans.copy || 'Copy')).removeClass('btn-danger').addClass('btn-primary');
            }, 2000);
        }

        tempInput.remove();
    }

    // Redirect to user view page when modal is closed
    $('#password-reset-success-modal').on('hidden.bs.modal', function () {
        // Extract user ID from the current URL
        var currentPath = window.location.pathname;
        var match = currentPath.match(/\/user\/(view|reset-password)\?id=(\d+)/) ||
                    window.location.search.match(/[?&]id=(\d+)/);

        if (match) {
            var userId = match[match.length - 1]; // Get the last capture group (the ID)
            window.location.href = '/user/view?id=' + userId;
        } else {
            // Fallback to reload if we can't find the ID
            location.reload();
        }
    });
}
