/**
 * @fileoverview Manages the conversation creation functionality.
 * This file handles:
 * - User selection interface using Select2
 * - Member management for new conversations
 * - Form submission with member data
 * - UI updates and validation
 */

/**
 * Initializes conversation creation functionality when the document is ready.
 * Sets up:
 * - Select2 dropdown for user selection
 * - Member tracking and management
 * - Form handling
 * @function
 */
$(document).ready(function() {
    $('.select2').select2({
        theme: 'bootstrap-5',
        width: '100%',
        placeholder: 'Search for a user...',
        allowClear: true
    });

    // Keep track of added members
    var addedMembers = new Set();
    var creatorId = document.querySelector('.member-row').dataset.userId;
    addedMembers.add(creatorId);

    // If in edit mode, add existing members to the set
    if (document.querySelector('.member-row[data-user-id]')) {
        document.querySelectorAll('.member-row[data-user-id]').forEach(function(row) {
            var memberId = String(row.dataset.userId);
            console.log('Adding existing member:', memberId);
            addedMembers.add(memberId);
        });
    }

    /**
     * Shows an alert modal with the specified message.
     * @function
     * @param {string} message - The message to display in the alert modal
     */
    function showAlert(message) {
        $('#alertModalMessage').text(message);
        var alertModal = new bootstrap.Modal(document.getElementById('alertModal'));
        alertModal.show();
    }

    /**
     * Handles adding a new member to the conversation.
     * Validates the selection and updates the UI accordingly.
     * @event
     */
    $('#addMemberBtn').click(function() {
        var selectedUserId = String($('#user_id').val());
        var selectedUserName = $('#user_id option:selected').text();
        var selectedUserEmail = $('#user_id option:selected').data('email') || '';
        var selectedUserAvatar = $('#user_id option:selected').data('avatar') || "/static/default-avatar.png";
        
        if (!selectedUserId) {
            showAlert('Please select a user to add.');
            return;
        }

        if (addedMembers.has(selectedUserId)) {
            showAlert('This user has already been added.');
            return;
        }

        console.log('Adding new member:', selectedUserId);
        // Add to the set of added members
        addedMembers.add(selectedUserId);

        // Disable the option in the dropdown
        $('#user_id option[value="' + selectedUserId + '"]').prop('disabled', true);
        $('#user_id').val(null).trigger('change');

        // Create the member list item
        var memberItem = $('<div class="list-group-item d-flex align-items-center member-row" data-user-id="' + selectedUserId + '">')
            .append($('<img class="member-avatar">').attr('src', selectedUserAvatar))
            .append($('<div class="flex-grow-1">')
                .append($('<div class="fw-bold">').text(selectedUserName))
                .append($('<div class="text-muted small">').text(selectedUserEmail))
            )
            .append($('<button type="button" class="btn btn-remove-member ms-2">')
                .append($('<i class="fas fa-user-minus me-1"></i>'))
                .append('Remove')
            );

        // Add to the list
        $('#selectedMembersList').append(memberItem);

        // Update hidden inputs
        updateHiddenInputs();
    });

    /**
     * Updates the hidden form inputs with the current member list.
     * Removes existing member inputs and adds new ones for each current member.
     * @function
     */
    function updateHiddenInputs() {
        // Remove any existing members inputs
        $('#conversationForm input[name="members"]').remove();
        
        console.log('Current members in Set:', Array.from(addedMembers));
        
        // Add new hidden inputs for each member
        addedMembers.forEach(function(memberId) {
            var input = $('<input>')
                .attr('type', 'hidden')
                .attr('name', 'members')
                .val(memberId);
            $('#conversationForm').append(input);
        });
    }

    // Initialize hidden inputs
    updateHiddenInputs();

    // Add click handler for remove buttons (both existing and new)
    $(document).on('click', '.btn-remove-member', function(e) {
        e.preventDefault();
        var memberRow = $(this).closest('.member-row');
        var memberId = String(memberRow.data('user-id'));
        
        console.log('Removing member:', memberId);
        console.log('Current members before removal:', Array.from(addedMembers));
        
        // Don't allow removing the creator
        if (memberId === creatorId) {
            return;
        }

        memberRow.remove();
        addedMembers.delete(memberId);
        console.log('Current members after removal:', Array.from(addedMembers));
        
        // Re-enable the option in the dropdown
        $('#user_id option[value="' + memberId + '"]').prop('disabled', false);
        $('#user_id').trigger('change');
        updateHiddenInputs();
    });
}); 