/**
 * Assignment System
 * 
 * This module handles member assignments, including assigning members,
 * unassigning members, and managing assignment data.
 */

// Assignment system namespace
const AssignmentSystem = (function() {
    /**
     * Initialize the assignment system
     */
    function init() {
        // Set up event listeners
        setupEventListeners();
        
        // Initialize any components
        initializeComponents();
    }
    
    /**
     * Set up event listeners
     */
    function setupEventListeners() {
        // Assignment form submission
        const assignForm = document.getElementById('assign-member-form');
        if (assignForm) {
            assignForm.addEventListener('submit', handleAssignFormSubmit);
        }
        
        // Unassignment buttons
        document.addEventListener('click', function(event) {
            if (event.target.matches('.unassign-btn') || event.target.closest('.unassign-btn')) {
                const button = event.target.matches('.unassign-btn') ? event.target : event.target.closest('.unassign-btn');
                const assignmentId = button.dataset.assignmentId;
                
                if (assignmentId) {
                    handleUnassignButtonClick(assignmentId);
                }
            }
        });
        
        // Transfer form submission
        const transferForm = document.getElementById('transfer-assignments-form');
        if (transferForm) {
            transferForm.addEventListener('submit', handleTransferFormSubmit);
        }
    }
    
    /**
     * Initialize components
     */
    function initializeComponents() {
        // Initialize DataTables if present
        if ($.fn.DataTable) {
            const assignmentTables = document.querySelectorAll('.assignment-datatable');
            assignmentTables.forEach(table => {
                $(table).DataTable({
                    responsive: true,
                    lengthChange: false,
                    autoWidth: false,
                    pageLength: 10
                });
            });
        }
        
        // Initialize Select2 if present
        if ($.fn.select2) {
            const selects = document.querySelectorAll('.select2');
            selects.forEach(select => {
                $(select).select2({
                    theme: 'bootstrap4'
                });
            });
        }
        
        // Load statistics if on dashboard
        const statsContainer = document.getElementById('assignment-stats');
        if (statsContainer) {
            loadAssignmentStats();
        }
    }
    
    /**
     * Handle assignment form submission
     * 
     * @param {Event} event Form submit event
     */
    function handleAssignFormSubmit(event) {
        event.preventDefault();
        
        // Get form data
        const form = event.target;
        const memberId = form.querySelector('[name="member_id"]').value;
        const assignedTo = form.querySelector('[name="assigned_to"]').value;
        const assignmentType = form.querySelector('[name="assignment_type"]')?.value || 'review';
        const priority = form.querySelector('[name="priority"]')?.value || 'normal';
        const notes = form.querySelector('[name="notes"]')?.value || '';
        const dueDate = form.querySelector('[name="due_date"]')?.value || null;
        
        // Validate form data
        if (!memberId || !assignedTo) {
            showToast('error', 'Please fill in all required fields');
            return;
        }
        
        // Show loading state
        const submitButton = form.querySelector('[type="submit"]');
        const originalText = submitButton.innerHTML;
        submitButton.disabled = true;
        submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Assigning...';
        
        // Send API request
        assignMember(memberId, assignedTo, assignmentType, priority, notes, dueDate)
            .then(response => {
                if (response.success) {
                    // Show success message
                    showToast('success', response.message);
                    
                    // Reset form
                    form.reset();
                    
                    // Reload member assignments if on member page
                    if (window.location.pathname.includes('member-view.php') || 
                        window.location.pathname.includes('member-edit.php')) {
                        loadMemberAssignments(memberId);
                    }
                    
                    // Reload assigned members if on admin page
                    if (window.location.pathname.includes('admin-view.php')) {
                        loadAssignedMembers(assignedTo);
                    }
                    
                    // Close modal if exists
                    if ($('#assign-modal').length) {
                        $('#assign-modal').modal('hide');
                    }
                } else {
                    // Show error message
                    showToast('error', response.message);
                }
            })
            .catch(error => {
                console.error('Error assigning member:', error);
                showToast('error', 'An error occurred while assigning the member');
            })
            .finally(() => {
                // Reset button state
                submitButton.disabled = false;
                submitButton.innerHTML = originalText;
            });
    }
    
    /**
     * Handle unassign button click
     * 
     * @param {string} assignmentId Assignment ID
     */
    function handleUnassignButtonClick(assignmentId) {
        // Show confirmation dialog
        Swal.fire({
            title: 'Unassign Member',
            text: 'Are you sure you want to unassign this member?',
            icon: 'warning',
            input: 'text',
            inputPlaceholder: 'Reason for unassignment (optional)',
            showCancelButton: true,
            confirmButtonText: 'Unassign',
            confirmButtonColor: '#dc3545',
            cancelButtonText: 'Cancel',
            showLoaderOnConfirm: true,
            preConfirm: (reason) => {
                return unassignMember(assignmentId, reason)
                    .then(response => {
                        if (!response.success) {
                            throw new Error(response.message);
                        }
                        return response;
                    })
                    .catch(error => {
                        Swal.showValidationMessage(
                            `Request failed: ${error.message || 'Unknown error'}`
                        );
                    });
            },
            allowOutsideClick: () => !Swal.isLoading()
        }).then((result) => {
            if (result.isConfirmed) {
                // Show success message
                Swal.fire({
                    title: 'Unassigned!',
                    text: result.value.message,
                    icon: 'success'
                });
                
                // Reload data based on current page
                if (window.location.pathname.includes('member-view.php') || 
                    window.location.pathname.includes('member-edit.php')) {
                    // Get member ID from URL
                    const urlParams = new URLSearchParams(window.location.search);
                    const memberId = urlParams.get('id');
                    if (memberId) {
                        loadMemberAssignments(memberId);
                    }
                } else if (window.location.pathname.includes('admin-view.php')) {
                    // Get admin ID from URL
                    const urlParams = new URLSearchParams(window.location.search);
                    const adminId = urlParams.get('id');
                    if (adminId) {
                        loadAssignedMembers(adminId, 'admin');
                    }
                } else if (window.location.pathname.includes('group-view.php')) {
                    // Get group ID from URL
                    const urlParams = new URLSearchParams(window.location.search);
                    const groupId = urlParams.get('id');
                    if (groupId) {
                        loadAssignedMembers(groupId, 'group');
                    }
                }
            }
        });
    }
    
    /**
     * Handle transfer form submission
     * 
     * @param {Event} event Form submit event
     */
    function handleTransferFormSubmit(event) {
        event.preventDefault();
        
        // Get form data
        const form = event.target;
        const fromAdmin = form.querySelector('[name="from_admin"]').value;
        const toAdmin = form.querySelector('[name="to_admin"]').value;
        const notes = form.querySelector('[name="notes"]')?.value || '';
        const assignmentType = form.querySelector('[name="assignment_type"]')?.value || '';
        const priority = form.querySelector('[name="priority"]')?.value || '';
        
        // Validate form data
        if (!fromAdmin || !toAdmin) {
            showToast('error', 'Please fill in all required fields');
            return;
        }
        
        // Confirm before transfer
        Swal.fire({
            title: 'Transfer Assignments',
            text: `Are you sure you want to transfer all assignments from admin #${fromAdmin} to admin #${toAdmin}?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Transfer',
            confirmButtonColor: '#007bff',
            cancelButtonText: 'Cancel',
            showLoaderOnConfirm: true,
            preConfirm: () => {
                return transferAssignments(fromAdmin, toAdmin, notes, assignmentType, priority)
                    .then(response => {
                        if (!response.success) {
                            throw new Error(response.message);
                        }
                        return response;
                    })
                    .catch(error => {
                        Swal.showValidationMessage(
                            `Request failed: ${error.message || 'Unknown error'}`
                        );
                    });
            },
            allowOutsideClick: () => !Swal.isLoading()
        }).then((result) => {
            if (result.isConfirmed) {
                // Show success message
                Swal.fire({
                    title: 'Transferred!',
                    text: result.value.message,
                    icon: 'success'
                });
                
                // Reset form
                form.reset();
                
                // Reload data if needed
                if (window.location.pathname.includes('admin-view.php')) {
                    // Get admin ID from URL
                    const urlParams = new URLSearchParams(window.location.search);
                    const adminId = urlParams.get('id');
                    if (adminId && (adminId == fromAdmin || adminId == toAdmin)) {
                        loadAssignedMembers(adminId);
                    }
                }
                
                // Close modal if exists
                if ($('#transfer-modal').length) {
                    $('#transfer-modal').modal('hide');
                }
            }
        });
    }
    
    /**
     * Assign a member
     * 
     * @param {string} memberId Member ID
     * @param {string} assignedTo Assigned to ID (admin ID)
     * @param {string} assignmentType Type of assignment ('review', 'approval', 'verification', 'follow_up')
     * @param {string} priority Priority ('low', 'normal', 'high', 'urgent')
     * @param {string} notes Optional notes
     * @param {string} dueDate Optional due date
     * @return {Promise} Promise with response
     */
    function assignMember(memberId, assignedTo, assignmentType = 'review', priority = 'normal', notes = '', dueDate = null) {
        return fetch('/api/assignments/assign.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                member_id: memberId,
                assigned_to: assignedTo,
                assignment_type: assignmentType,
                priority: priority,
                notes: notes,
                due_date: dueDate
            })
        })
        .then(response => response.json());
    }
    
    /**
     * Unassign a member
     * 
     * @param {string} assignmentId Assignment ID
     * @param {string} reason Optional reason for unassignment
     * @return {Promise} Promise with response
     */
    function unassignMember(assignmentId, reason = '') {
        return fetch('/api/assignments/unassign.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                assignment_id: assignmentId,
                reason: reason,
                status: 'cancelled'
            })
        })
        .then(response => response.json());
    }
    
    /**
     * Transfer assignments
     * 
     * @param {string} fromId Source admin ID
     * @param {string} toId Target admin ID
     * @param {string} notes Optional notes
     * @param {string} assignmentType Optional filter by assignment type
     * @param {string} priority Optional filter by priority
     * @return {Promise} Promise with response
     */
    function transferAssignments(fromId, toId, notes = '', assignmentType = '', priority = '') {
        return fetch('/api/assignments/transfer.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                from_admin: fromId,
                to_admin: toId,
                notes: notes,
                assignment_type: assignmentType,
                priority: priority
            })
        })
        .then(response => response.json());
    }
    
    /**
     * Load member assignments
     * 
     * @param {string} memberId Member ID
     */
    function loadMemberAssignments(memberId) {
        const container = document.getElementById('member-assignments-container');
        if (!container) return;
        
        // Show loading
        container.innerHTML = '<div class="text-center p-3"><i class="fas fa-spinner fa-spin fa-2x"></i><p>Loading assignments...</p></div>';
        
        // Fetch assignments
        fetch(`/api/assignments/list-member.php?member_id=${memberId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    renderMemberAssignments(container, data.data);
                } else {
                    container.innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
                }
            })
            .catch(error => {
                console.error('Error loading member assignments:', error);
                container.innerHTML = '<div class="alert alert-danger">Error loading assignments</div>';
            });
    }
    
    /**
     * Render member assignments
     * 
     * @param {HTMLElement} container Container element
     * @param {Array} assignments Array of assignment objects
     */
    function renderMemberAssignments(container, assignments) {
        if (!assignments || assignments.length === 0) {
            container.innerHTML = '<div class="alert alert-info">No assignments found for this member</div>';
            return;
        }
        
        // Build HTML
        let html = `
            <div class="table-responsive">
                <table class="table table-bordered table-striped assignment-datatable">
                    <thead>
                        <tr>
                            <th>Assigned To</th>
                            <th>Type</th>
                            <th>Priority</th>
                            <th>Due Date</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
        `;
        
        assignments.forEach(assignment => {
            const createdAt = new Date(assignment.created_at);
            const formattedCreatedDate = createdAt.toLocaleDateString();
            
            let dueDateStr = 'Not set';
            if (assignment.due_date) {
                const dueDate = new Date(assignment.due_date);
                dueDateStr = dueDate.toLocaleDateString();
            }
            
            // Get status badge class
            let statusBadgeClass = 'badge-secondary';
            switch (assignment.status) {
                case 'active':
                    statusBadgeClass = 'badge-success';
                    break;
                case 'completed':
                    statusBadgeClass = 'badge-info';
                    break;
                case 'cancelled':
                    statusBadgeClass = 'badge-secondary';
                    break;
                case 'overdue':
                    statusBadgeClass = 'badge-danger';
                    break;
            }
            
            // Get priority badge class
            let priorityBadgeClass = 'badge-info';
            switch (assignment.priority) {
                case 'low':
                    priorityBadgeClass = 'badge-secondary';
                    break;
                case 'normal':
                    priorityBadgeClass = 'badge-info';
                    break;
                case 'high':
                    priorityBadgeClass = 'badge-warning';
                    break;
                case 'urgent':
                    priorityBadgeClass = 'badge-danger';
                    break;
            }
            
            html += `
                <tr>
                    <td>${assignment.admin_name || 'Unknown'}</td>
                    <td>${assignment.assignment_type.replace('_', ' ').toUpperCase()}</td>
                    <td><span class="badge ${priorityBadgeClass}">${assignment.priority.toUpperCase()}</span></td>
                    <td>${dueDateStr}</td>
                    <td>
                        <span class="badge ${statusBadgeClass}">${assignment.status.toUpperCase()}</span>
                    </td>
                    <td>
                        ${assignment.status === 'active' 
                            ? `<button type="button" class="btn btn-sm btn-danger unassign-btn" data-assignment-id="${assignment.id}">
                                <i class="fas fa-user-minus"></i> Cancel
                               </button>` 
                            : `<span class="text-muted">Completed by ${assignment.completed_by_name || 'System'}</span>`}
                    </td>
                </tr>
            `;
        });
        
        html += `
                    </tbody>
                </table>
            </div>
        `;
        
        // Update container
        container.innerHTML = html;
        
        // Initialize DataTable
        if ($.fn.DataTable) {
            $(container).find('.assignment-datatable').DataTable({
                responsive: true,
                lengthChange: false,
                autoWidth: false,
                pageLength: 10
            });
        }
    }
    
    /**
     * Load assigned members
     * 
     * @param {string} adminId Admin ID
     * @param {string} status Filter by status ('active', 'completed', 'cancelled', 'overdue', or '' for all)
     */
    function loadAssignedMembers(adminId, status = 'active') {
        const container = document.getElementById('assigned-members-container');
        if (!container) return;
        
        // Show loading
        container.innerHTML = '<div class="text-center p-3"><i class="fas fa-spinner fa-spin fa-2x"></i><p>Loading assigned members...</p></div>';
        
        // Fetch assigned members
        fetch(`/api/assignments/list-assigned.php?assigned_to=${adminId}${status ? '&status=' + status : ''}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    renderAssignedMembers(container, data.data);
                } else {
                    container.innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
                }
            })
            .catch(error => {
                console.error('Error loading assigned members:', error);
                container.innerHTML = '<div class="alert alert-danger">Error loading assigned members</div>';
            });
    }
    
    /**
     * Render assigned members
     * 
     * @param {HTMLElement} container Container element
     * @param {Array} assignments Array of assignments objects
     */
    function renderAssignedMembers(container, assignments) {
        if (!assignments || assignments.length === 0) {
            container.innerHTML = '<div class="alert alert-info">No members assigned</div>';
            return;
        }
        
        // Build HTML
        let html = `
            <div class="table-responsive">
                <table class="table table-bordered table-striped assignment-datatable">
                    <thead>
                        <tr>
                            <th>Member ID</th>
                            <th>Name</th>
                            <th>Type</th>
                            <th>Priority</th>
                            <th>Due Date</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
        `;
        
        assignments.forEach(assignment => {
            const createdAt = new Date(assignment.created_at);
            const formattedCreatedDate = createdAt.toLocaleDateString();
            
            let dueDateStr = 'Not set';
            if (assignment.due_date) {
                const dueDate = new Date(assignment.due_date);
                dueDateStr = dueDate.toLocaleDateString();
            }
            
            // Get status badge class
            let statusBadgeClass = 'badge-secondary';
            switch (assignment.status) {
                case 'active':
                    statusBadgeClass = 'badge-success';
                    break;
                case 'completed':
                    statusBadgeClass = 'badge-info';
                    break;
                case 'cancelled':
                    statusBadgeClass = 'badge-secondary';
                    break;
                case 'overdue':
                    statusBadgeClass = 'badge-danger';
                    break;
            }
            
            // Get priority badge class
            let priorityBadgeClass = 'badge-info';
            switch (assignment.priority) {
                case 'low':
                    priorityBadgeClass = 'badge-secondary';
                    break;
                case 'normal':
                    priorityBadgeClass = 'badge-info';
                    break;
                case 'high':
                    priorityBadgeClass = 'badge-warning';
                    break;
                case 'urgent':
                    priorityBadgeClass = 'badge-danger';
                    break;
            }
            
            html += `
                <tr>
                    <td>${assignment.kso_id || 'N/A'}</td>
                    <td>
                        <a href="/adminlte/member-view.php?id=${assignment.member_id}">
                            ${assignment.first_name} ${assignment.last_name}
                        </a>
                    </td>
                    <td>${assignment.assignment_type.replace('_', ' ').toUpperCase()}</td>
                    <td><span class="badge ${priorityBadgeClass}">${assignment.priority.toUpperCase()}</span></td>
                    <td>${dueDateStr}</td>
                    <td>
                        <span class="badge ${statusBadgeClass}">${assignment.status.toUpperCase()}</span>
                    </td>
                    <td>
                        ${assignment.status === 'active' ? `
                        <div class="btn-group">
                            <button type="button" class="btn btn-sm btn-danger unassign-btn" data-assignment-id="${assignment.id}">
                                <i class="fas fa-times"></i> Cancel
                            </button>
                            <button type="button" class="btn btn-sm btn-success complete-btn" data-assignment-id="${assignment.id}">
                                <i class="fas fa-check"></i> Complete
                            </button>
                        </div>
                        ` : ''}
                        <a href="/adminlte/member-view.php?id=${assignment.member_id}" class="btn btn-sm btn-info">
                            <i class="fas fa-eye"></i> View
                        </a>
                    </td>
                </tr>
            `;
        });
        
        html += `
                    </tbody>
                </table>
            </div>
        `;
        
        // Update container
        container.innerHTML = html;
        
        // Initialize DataTable
        if ($.fn.DataTable) {
            $(container).find('.assignment-datatable').DataTable({
                responsive: true,
                lengthChange: false,
                autoWidth: false,
                pageLength: 10
            });
        }
    }
    
    /**
     * Load assignment statistics
     */
    function loadAssignmentStats() {
        const container = document.getElementById('assignment-stats');
        if (!container) return;
        
        // Show loading
        container.innerHTML = '<div class="text-center p-3"><i class="fas fa-spinner fa-spin fa-2x"></i><p>Loading statistics...</p></div>';
        
        // Fetch statistics
        fetch('/api/assignments/stats.php')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    renderAssignmentStats(container, data.data);
                } else {
                    container.innerHTML = `<div class="alert alert-danger">${data.message}</div>`;
                }
            })
            .catch(error => {
                console.error('Error loading assignment statistics:', error);
                container.innerHTML = '<div class="alert alert-danger">Error loading statistics</div>';
            });
    }
    
    /**
     * Render assignment statistics
     * 
     * @param {HTMLElement} container Container element
     * @param {Object} stats Statistics object
     */
    function renderAssignmentStats(container, stats) {
        // Build HTML
        let html = `
            <div class="row">
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-info">
                        <div class="inner">
                            <h3>${stats.total_assignments}</h3>
                            <p>Total Assignments</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-tasks"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-success">
                        <div class="inner">
                            <h3>${stats.active_assignments}</h3>
                            <p>Active Assignments</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-spinner"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-warning">
                        <div class="inner">
                            <h3>${stats.completed_assignments}</h3>
                            <p>Completed Assignments</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-danger">
                        <div class="inner">
                            <h3>${stats.overdue_assignments}</h3>
                            <p>Overdue Assignments</p>
                        </div>
                        <div class="icon">
                            <i class="fas fa-exclamation-circle"></i>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Top Admins</h3>
                        </div>
                        <div class="card-body p-0">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Admin</th>
                                        <th>Assigned Members</th>
                                    </tr>
                                </thead>
                                <tbody>
        `;
        
        if (stats.top_admins && stats.top_admins.length > 0) {
            stats.top_admins.forEach(admin => {
                html += `
                    <tr>
                        <td>
                            <a href="/adminlte/admin-view.php?id=${admin.id}">
                                ${admin.username}
                            </a>
                        </td>
                        <td>
                            <span class="badge bg-primary">${admin.assignments_count}</span>
                        </td>
                    </tr>
                `;
            });
        } else {
            html += '<tr><td colspan="2" class="text-center">No data available</td></tr>';
        }
        
        html += `
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Assignment Types</h3>
                        </div>
                        <div class="card-body p-0">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Type</th>
                                        <th>Count</th>
                                    </tr>
                                </thead>
                                <tbody>
        `;
        
        if (stats.by_type && stats.by_type.length > 0) {
            stats.by_type.forEach(type => {
                html += `
                    <tr>
                        <td>${type.assignment_type.replace('_', ' ').toUpperCase()}</td>
                        <td>
                            <span class="badge bg-success">${type.count}</span>
                        </td>
                    </tr>
                `;
            });
        } else {
            html += '<tr><td colspan="2" class="text-center">No data available</td></tr>';
        }
        
        html += `
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Recent Assignments</h3>
                        </div>
                        <div class="card-body p-0">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Member</th>
                                        <th>Assigned To</th>
                                        <th>Type</th>
                                        <th>Priority</th>
                                        <th>Status</th>
                                        <th>Due Date</th>
                                    </tr>
                                </thead>
                                <tbody>
        `;
        
        if (stats.recent_assignments && stats.recent_assignments.length > 0) {
            stats.recent_assignments.forEach(assignment => {
                const createdAt = new Date(assignment.created_at);
                const formattedCreatedDate = createdAt.toLocaleDateString();
                
                let dueDateStr = 'Not set';
                if (assignment.due_date) {
                    const dueDate = new Date(assignment.due_date);
                    dueDateStr = dueDate.toLocaleDateString();
                }
                
                // Get priority badge class
                let priorityBadgeClass = 'badge-info';
                switch (assignment.priority) {
                    case 'low':
                        priorityBadgeClass = 'badge-secondary';
                        break;
                    case 'normal':
                        priorityBadgeClass = 'badge-info';
                        break;
                    case 'high':
                        priorityBadgeClass = 'badge-warning';
                        break;
                    case 'urgent':
                        priorityBadgeClass = 'badge-danger';
                        break;
                }
                
                // Get status badge class
                let statusBadgeClass = 'badge-secondary';
                switch (assignment.status) {
                    case 'active':
                        statusBadgeClass = 'badge-success';
                        break;
                    case 'completed':
                        statusBadgeClass = 'badge-info';
                        break;
                    case 'cancelled':
                        statusBadgeClass = 'badge-secondary';
                        break;
                    case 'overdue':
                        statusBadgeClass = 'badge-danger';
                        break;
                }
                
                html += `
                    <tr>
                        <td>${assignment.first_name} ${assignment.last_name}</td>
                        <td>${assignment.admin_name || 'Unknown'}</td>
                        <td>${assignment.assignment_type.replace('_', ' ').toUpperCase()}</td>
                        <td><span class="badge ${priorityBadgeClass}">${assignment.priority.toUpperCase()}</span></td>
                        <td><span class="badge ${statusBadgeClass}">${assignment.status.toUpperCase()}</span></td>
                        <td>${dueDateStr}</td>
                    </tr>
                `;
            });
        } else {
            html += '<tr><td colspan="6" class="text-center">No recent assignments</td></tr>';
        }
        
        html += `
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // Update container
        container.innerHTML = html;
    }
    
    /**
     * Show toast notification
     * 
     * @param {string} type Notification type ('success', 'error', 'info', 'warning')
     * @param {string} message Message to display
     */
    function showToast(type, message) {
        const Toast = Swal.mixin({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000,
            timerProgressBar: true
        });
        
        Toast.fire({
            icon: type,
            title: message
        });
    }
    
    // Public API
    return {
        init,
        assignMember,
        unassignMember,
        transferAssignments,
        loadMemberAssignments,
        loadAssignedMembers,
        loadAssignmentStats
    };
})();

// Initialize assignment system when document is ready
document.addEventListener('DOMContentLoaded', function() {
    AssignmentSystem.init();
});
