// Admin Bulk Operations and Search Functionality
class AdminActions {
    constructor() {
        this.selectedPlayers = new Set();
        this.selectedCoaches = new Set();
        this.init();
    }

    init() {
        this.setupBulkActions();
        this.setupLiveSearch();
        this.setupSelectAll();
    }

    // Bulk Operations
    setupBulkActions() {
        // Player checkboxes
        document.querySelectorAll('.player-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', (e) => {
                this.handlePlayerSelection(e.target);
            });
        });

        // Coach checkboxes
        document.querySelectorAll('.coach-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', (e) => {
                this.handleCoachSelection(e.target);
            });
        });

        // Apply bulk action
        document.getElementById('applyBulkAction')?.addEventListener('click', () => {
            this.applyBulkAction();
        });

        // Clear selection
        document.getElementById('clearSelection')?.addEventListener('click', () => {
            this.clearSelection();
        });
    }

    handlePlayerSelection(checkbox) {
        const playerId = checkbox.value;
        const playerCard = checkbox.closest('.player-admin-card');

        if (checkbox.checked) {
            this.selectedPlayers.add(playerId);
            playerCard.classList.add('selected');
        } else {
            this.selectedPlayers.delete(playerId);
            playerCard.classList.remove('selected');
        }

        this.updateBulkActionsUI('players');
    }

    handleCoachSelection(checkbox) {
        const coachId = checkbox.value;
        const coachCard = checkbox.closest('.coach-admin-card');

        if (checkbox.checked) {
            this.selectedCoaches.add(coachId);
            coachCard.classList.add('selected');
        } else {
            this.selectedCoaches.delete(coachId);
            coachCard.classList.remove('selected');
        }

        this.updateBulkActionsUI('coaches');
    }

    updateBulkActionsUI(type) {
        const selectedCount = type === 'players' ? this.selectedPlayers.size : this.selectedCoaches.size;
        const bulkActions = document.getElementById('bulkActions');
        const selectedCountElement = document.getElementById('bulkSelectedCount');

        if (selectedCountElement) {
            selectedCountElement.textContent = `${selectedCount} ${type} selected`;
        }

        if (bulkActions) {
            if (selectedCount > 0) {
                bulkActions.classList.add('active');
            } else {
                bulkActions.classList.remove('active');
            }
        }

        // Update select all checkbox
        const selectAll = document.getElementById(`selectAll${type.charAt(0).toUpperCase() + type.slice(1)}`);
        if (selectAll) {
            const totalCount = document.querySelectorAll(`.${type}-grid .${type}-admin-card`).length;
            selectAll.checked = selectedCount === totalCount && totalCount > 0;
            selectAll.indeterminate = selectedCount > 0 && selectedCount < totalCount;
        }
    }

    applyBulkAction() {
        const actionSelect = document.getElementById('bulkActionSelect');
        const selectedAction = actionSelect.value;
        const currentPage = window.location.pathname.includes('coaches') ? 'coaches' : 'players';

        if (!selectedAction) {
            alert('Please select an action to perform.');
            return;
        }

        const selectedIds = currentPage === 'players' ? Array.from(this.selectedPlayers) : Array.from(this.selectedCoaches);

        if (selectedIds.length === 0) {
            alert('Please select at least one item to perform the action.');
            return;
        }

        if (selectedAction === 'delete') {
            const confirmMessage = `Are you sure you want to delete ${selectedIds.length} ${currentPage}? This action cannot be undone.`;
            if (!confirm(confirmMessage)) {
                return;
            }
        }

        // Submit bulk action form
        const form = document.getElementById('bulkActionForm');
        const actionInput = document.getElementById('bulkActionInput');
        const container = document.getElementById('bulkPlayersContainer');

        actionInput.value = selectedAction;
        container.innerHTML = '';

        selectedIds.forEach(id => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = currentPage === 'players' ? 'player_ids[]' : 'coach_ids[]';
            input.value = id;
            container.appendChild(input);
        });

        form.submit();
    }

    clearSelection() {
        this.selectedPlayers.clear();
        this.selectedCoaches.clear();

        // Uncheck all checkboxes
        document.querySelectorAll('.player-checkbox, .coach-checkbox').forEach(checkbox => {
            checkbox.checked = false;
        });

        // Remove selected class
        document.querySelectorAll('.player-admin-card.selected, .coach-admin-card.selected').forEach(card => {
            card.classList.remove('selected');
        });

        this.updateBulkActionsUI('players');
        this.updateBulkActionsUI('coaches');
    }

    // Select All functionality
    setupSelectAll() {
        // Players select all
        document.getElementById('selectAllPlayers')?.addEventListener('change', (e) => {
            const checkboxes = document.querySelectorAll('.player-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = e.target.checked;
                checkbox.dispatchEvent(new Event('change'));
            });
        });

        // Coaches select all
        document.getElementById('selectAllCoaches')?.addEventListener('change', (e) => {
            const checkboxes = document.querySelectorAll('.coach-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = e.target.checked;
                checkbox.dispatchEvent(new Event('change'));
            });
        });
    }

    // Live Search Functionality
    setupLiveSearch() {
        const searchInputs = document.querySelectorAll('.live-search');
        
        searchInputs.forEach(input => {
            let timeout;
            
            input.addEventListener('input', (e) => {
                clearTimeout(timeout);
                timeout = setTimeout(() => {
                    this.performLiveSearch(e.target);
                }, 300);
            });

            // Also search on Enter key
            input.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    this.performLiveSearch(input);
                }
            });
        });

        // Auto-submit filter changes
        document.querySelectorAll('select[name="game_week"], select[name="position"], select[name="status"]').forEach(select => {
            select.addEventListener('change', () => {
                document.getElementById('searchForm').submit();
            });
        });
    }

    performLiveSearch(input) {
        const searchTerm = input.value.trim();
        const searchType = input.dataset.searchType;
        const form = document.getElementById('searchForm');
        
        if (searchTerm.length === 0 || searchTerm.length >= 2) {
            // For now, we'll submit the form for server-side search
            // In a future enhancement, we can implement client-side filtering
            form.submit();
        }
    }

    // Utility function to show loading state
    showLoading(element) {
        const originalHTML = element.innerHTML;
        element.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
        element.disabled = true;

        return () => {
            element.innerHTML = originalHTML;
            element.disabled = false;
        };
    }

    // Utility function for API calls (for future AJAX implementation)
    async makeApiCall(endpoint, data) {
        try {
            const response = await fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            });

            return await response.json();
        } catch (error) {
            console.error('API call failed:', error);
            throw error;
        }
    }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    window.adminActions = new AdminActions();
    console.log('Admin actions initialized');
});

// Utility functions for modals
function openEditModal(data, type) {
    // Generic modal opener that can handle both players and coaches
    const modal = document.getElementById('editModal');
    const form = document.getElementById('editForm');
    
    // Set form action based on type
    if (type === 'player') {
        form.querySelector('input[name="player_id"]').value = data.id;
        form.querySelector('input[name="name"]').value = data.name;
        form.querySelector('select[name="position_id"]').value = data.position_id;
        form.querySelector('input[name="team"]').value = data.team;
        form.querySelector('input[name="game_week"]').value = data.game_week;
        form.querySelector('input[name="is_active"]').checked = data.is_active == 1;
    } else if (type === 'coach') {
        form.querySelector('input[name="coach_id"]').value = data.id;
        form.querySelector('input[name="name"]').value = data.name;
        form.querySelector('input[name="team"]').value = data.team;
        form.querySelector('input[name="game_week"]').value = data.game_week;
        form.querySelector('input[name="is_active"]').checked = data.is_active == 1;
    }
    
    modal.style.display = 'block';
}

function closeEditModal() {
    document.getElementById('editModal').style.display = 'none';
}