{% extends "base.html" %}

{% block title %}{{ page_title }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div>
                    <h1><i class="fas fa-list-ul me-2"></i>Fixtures</h1>
                    <p class="mb-0">View and manage synchronized boxing match fixtures.</p>
                </div>
                {% if current_user.is_admin %}
                <div>
                    <button type="button" class="btn btn-danger" id="reset-fixtures-btn">
                        <i class="fas fa-trash-alt me-1"></i>Reset All Fixtures
                    </button>
                </div>
                {% endif %}
            </div>
            
            <!-- Filters and Search -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5>Filter Options</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3">
                            <label for="status-filter" class="form-label">Status</label>
                            <select class="form-select" id="status-filter">
                                <option value="">All Status</option>
                                <option value="pending">Pending</option>
                                <option value="running">Running</option>
                                <option value="done">Completed</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="upload-filter" class="form-label">Upload Status</label>
                            <select class="form-select" id="upload-filter">
                                <option value="">All Uploads</option>
                                <option value="pending">Pending</option>
                                <option value="uploading">Uploading</option>
                                <option value="completed">Completed</option>
                                <option value="failed">Failed</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="search-input" class="form-label">Search Fighters</label>
                            <input type="text" class="form-control" id="search-input" placeholder="Search by fighter names or venue">
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button class="btn btn-primary" id="refresh-btn">
                                <i class="fas fa-sync-alt me-1"></i>Refresh
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Loading Spinner -->
            <div id="loading" class="text-center my-4" style="display: none;">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">Loading fixtures...</p>
            </div>
            
            <!-- Fixtures Summary Cards -->
            <div class="row mb-4" id="summary-cards">
                <div class="col-md-3">
                    <div class="card text-center">
                        <div class="card-body">
                            <h5 class="card-title text-primary">
                                <i class="fas fa-list me-2"></i>Total Fixtures
                            </h5>
                            <h3 id="total-count" class="text-primary">0</h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card text-center">
                        <div class="card-body">
                            <h5 class="card-title text-warning">
                                <i class="fas fa-clock me-2"></i>Pending
                            </h5>
                            <h3 id="pending-count" class="text-warning">0</h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card text-center">
                        <div class="card-body">
                            <h5 class="card-title text-info">
                                <i class="fas fa-play me-2"></i>Running
                            </h5>
                            <h3 id="running-count" class="text-info">0</h3>
                        </div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="card text-center">
                        <div class="card-body">
                            <h5 class="card-title text-success">
                                <i class="fas fa-check me-2"></i>Completed
                            </h5>
                            <h3 id="completed-count" class="text-success">0</h3>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Fixtures Table -->
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5>All Fixtures</h5>
                    <span id="filtered-count" class="badge bg-secondary">0 fixtures</span>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0" id="fixtures-table">
                            <thead class="table-light">
                                <tr>
                                    <th>Match #</th>
                                    <th>Fighters</th>
                                    <th>Venue</th>
                                    <th>Status</th>
                                    <th>Upload Status</th>
                                    <th>Created</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="fixtures-tbody">
                                <!-- Table content will be loaded here -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- Empty State -->
            <div id="empty-state" class="text-center my-5" style="display: none;">
                <i class="fas fa-inbox fa-4x text-muted mb-3"></i>
                <h4 class="text-muted">No Fixtures Found</h4>
                <p class="text-muted">No synchronized fixtures found. Check your API synchronization settings.</p>
            </div>
        </div>
    </div>
</div>

<script>
let allFixtures = [];

// Load fixtures on page load
document.addEventListener('DOMContentLoaded', function() {
    loadFixtures();
    
    // Event listeners
    document.getElementById('refresh-btn').addEventListener('click', loadFixtures);
    document.getElementById('status-filter').addEventListener('change', filterFixtures);
    document.getElementById('upload-filter').addEventListener('change', filterFixtures);
    document.getElementById('search-input').addEventListener('input', filterFixtures);
    
    // Reset fixtures button (admin only)
    const resetBtn = document.getElementById('reset-fixtures-btn');
    if (resetBtn) {
        resetBtn.addEventListener('click', resetFixtures);
    }
});

function loadFixtures() {
    const loading = document.getElementById('loading');
    const refreshBtn = document.getElementById('refresh-btn');
    
    loading.style.display = 'block';
    refreshBtn.disabled = true;
    
    fetch('/api/fixtures')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                allFixtures = data.fixtures;
                updateSummaryCards();
                filterFixtures(); // This will also render the table
            } else {
                alert('Error loading fixtures: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Failed to load fixtures: ' + error.message);
        })
        .finally(() => {
            loading.style.display = 'none';
            refreshBtn.disabled = false;
        });
}

function updateSummaryCards() {
    const totalCount = allFixtures.length;
    const pendingCount = allFixtures.filter(f => !f.running && !f.done).length;
    const runningCount = allFixtures.filter(f => f.running && !f.done).length;
    const completedCount = allFixtures.filter(f => f.done).length;
    
    document.getElementById('total-count').textContent = totalCount;
    document.getElementById('pending-count').textContent = pendingCount;
    document.getElementById('running-count').textContent = runningCount;
    document.getElementById('completed-count').textContent = completedCount;
}

function filterFixtures() {
    const statusFilter = document.getElementById('status-filter').value;
    const uploadFilter = document.getElementById('upload-filter').value;
    const searchTerm = document.getElementById('search-input').value.toLowerCase();
    
    let filteredFixtures = allFixtures.filter(fixture => {
        // Status filter
        if (statusFilter) {
            if (statusFilter === 'pending' && (fixture.running || fixture.done)) return false;
            if (statusFilter === 'running' && (!fixture.running || fixture.done)) return false;
            if (statusFilter === 'done' && !fixture.done) return false;
        }
        
        // Upload filter
        if (uploadFilter && fixture.zip_upload_status !== uploadFilter) {
            return false;
        }
        
        // Search filter
        if (searchTerm) {
            const searchText = (fixture.fighter1_township + ' ' + fixture.fighter2_township + ' ' + fixture.venue_kampala_township).toLowerCase();
            if (!searchText.includes(searchTerm)) return false;
        }
        
        return true;
    });
    
    renderFixturesTable(filteredFixtures);
    document.getElementById('filtered-count').textContent = filteredFixtures.length + ' fixtures';
    
    // Show/hide empty state
    const emptyState = document.getElementById('empty-state');
    const fixturesTable = document.querySelector('.card .table-responsive').parentElement;
    
    if (filteredFixtures.length === 0 && allFixtures.length === 0) {
        emptyState.style.display = 'block';
        fixturesTable.style.display = 'none';
    } else {
        emptyState.style.display = 'none';
        fixturesTable.style.display = 'block';
    }
}

function renderFixturesTable(fixtures) {
    const tbody = document.getElementById('fixtures-tbody');
    tbody.innerHTML = '';
    
    fixtures.forEach(fixture => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td><strong>#${fixture.match_number}</strong></td>
            <td>
                <div class="fw-bold">${fixture.fighter1_township}</div>
                <small class="text-muted">vs</small>
                <div class="fw-bold">${fixture.fighter2_township}</div>
            </td>
            <td>${fixture.venue_kampala_township}</td>
            <td>${getStatusBadge(fixture)}</td>
            <td>${getUploadStatusBadge(fixture)}</td>
            <td>
                <small class="text-muted">
                    ${new Date(fixture.created_at).toLocaleString()}
                </small>
            </td>
            <td>
                <a href="/fixtures/${fixture.id}" class="btn btn-sm btn-outline-primary">
                    <i class="fas fa-eye me-1"></i>Details
                </a>
            </td>
        `;
        tbody.appendChild(row);
    });
}

function getStatusBadge(fixture) {
    if (fixture.done) {
        return '<span class="badge bg-success"><i class="fas fa-check me-1"></i>Completed</span>';
    } else if (fixture.running) {
        return '<span class="badge bg-info"><i class="fas fa-play me-1"></i>Running</span>';
    } else {
        return '<span class="badge bg-warning"><i class="fas fa-clock me-1"></i>Pending</span>';
    }
}

function getUploadStatusBadge(fixture) {
    const status = fixture.zip_upload_status || 'pending';
    const progress = fixture.zip_upload_progress || 0;
    
    switch (status) {
        case 'completed':
            return '<span class="badge bg-success"><i class="fas fa-check me-1"></i>Completed</span>';
        case 'uploading':
            return `<span class="badge bg-info"><i class="fas fa-spinner fa-spin me-1"></i>Uploading (${progress.toFixed(1)}%)</span>`;
        case 'failed':
            return '<span class="badge bg-danger"><i class="fas fa-times me-1"></i>Failed</span>';
        default:
            return '<span class="badge bg-secondary"><i class="fas fa-clock me-1"></i>Pending</span>';
    }
}

function resetFixtures() {
    const confirmMessage = 'WARNING: This will permanently delete ALL fixture data including:\n\n' +
                          '• All synchronized matches and outcomes\n' +
                          '• All downloaded ZIP files\n' +
                          '• This action cannot be undone!\n\n' +
                          'Are you sure you want to reset all fixtures data?';
    
    if (!confirm(confirmMessage)) {
        return;
    }
    
    const resetBtn = document.getElementById('reset-fixtures-btn');
    const originalText = resetBtn.innerHTML;
    
    resetBtn.disabled = true;
    resetBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Resetting...';
    
    fetch('/api/fixtures/reset', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(`Fixtures reset successfully!\n\nRemoved:\n• ${data.removed.matches} matches\n• ${data.removed.outcomes} outcomes\n• ${data.removed.zip_files} ZIP files`);
            // Reload fixtures to show empty state
            loadFixtures();
        } else {
            alert('Error resetting fixtures: ' + (data.error || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to reset fixtures: ' + error.message);
    })
    .finally(() => {
        resetBtn.disabled = false;
        resetBtn.innerHTML = originalText;
    });
}
</script>
{% endblock %}