{% 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 with status tracking.</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="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-3">
                            <label for="past-filter" class="form-label">Past Fixtures</label>
                            <select class="form-select" id="past-filter">
                                <option value="hide">Hide Past</option>
                                <option value="show">Show Past</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>Fixture #</th>
                                    <th>Fighters</th>
                                    <th>Venue</th>
                                    <th>Status</th>
                                    <th>Upload Status</th>
                                    <th>Start Time</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 or upload fixture files.</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('upload-filter').addEventListener('change', filterFixtures);
    document.getElementById('past-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);
    }
    
    // Auto-refresh fixtures every 5 seconds
    setInterval(loadFixtures, 5000);
});

let isInitialLoad = true;

function loadFixtures() {
    const loading = document.getElementById('loading');
    const refreshBtn = document.getElementById('refresh-btn');
    
    // Only show loading spinner on initial load or manual refresh
    if (isInitialLoad || refreshBtn.disabled) {
        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 {
                if (isInitialLoad) {
                    alert('Error loading fixtures: ' + (data.error || 'Unknown error'));
                }
            }
        })
        .catch(error => {
            console.error('Error:', error);
            if (isInitialLoad) {
                alert('Failed to load fixtures: ' + error.message);
            }
        })
        .finally(() => {
            loading.style.display = 'none';
            refreshBtn.disabled = false;
            isInitialLoad = false;
        });
}

function updateSummaryCards() {
    const totalCount = allFixtures.length;
    const pendingCount = allFixtures.filter(f => f.fixture_status === 'pending').length;
    const runningCount = allFixtures.filter(f => f.fixture_status === 'running').length;
    const scheduledCount = allFixtures.filter(f => f.fixture_status === 'scheduled').length;
    const betCount = allFixtures.filter(f => f.fixture_status === 'bet').length;
    const ingameCount = allFixtures.filter(f => f.fixture_status === 'ingame').length;
    const endCount = allFixtures.filter(f => f.fixture_status === 'end').length;

    document.getElementById('total-count').textContent = totalCount;
    document.getElementById('pending-count').textContent = pendingCount;
    document.getElementById('running-count').textContent = runningCount;

    // Update the summary cards to show more status types
    const summaryCards = document.getElementById('summary-cards');
    const betInGameCount = betCount + ingameCount;
    summaryCards.innerHTML = `
        <div class="col-md-2">
            <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">` + totalCount + `</h3>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <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">` + pendingCount + `</h3>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <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">` + runningCount + `</h3>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-secondary">
                        <i class="fas fa-calendar me-2"></i>Scheduled
                    </h5>
                    <h3 class="text-secondary">` + scheduledCount + `</h3>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-success">
                        <i class="fas fa-gamepad me-2"></i>Bet/In Game
                    </h5>
                    <h3 class="text-success">` + betInGameCount + `</h3>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="card text-center">
                <div class="card-body">
                    <h5 class="card-title text-dark">
                        <i class="fas fa-stop me-2"></i>End
                    </h5>
                    <h3 class="text-dark">` + endCount + `</h3>
                </div>
            </div>
        </div>
    `;
}

function filterFixtures() {
    const uploadFilter = document.getElementById('upload-filter').value;
    const pastFilter = document.getElementById('past-filter').value;
    const searchTerm = document.getElementById('search-input').value.toLowerCase();

    // Get today's date (start of day)
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    let filteredFixtures = allFixtures.filter(fixture => {
        // Past fixtures filter
        if (pastFilter === 'hide') {
            // Hide past fixtures by default
            if (fixture.start_time) {
                const fixtureDate = new Date(fixture.start_time);
                fixtureDate.setHours(0, 0, 0, 0);
                if (fixtureDate < today) {
                    return false; // Hide past fixtures
                }
            }
            // Show fixtures with no start_time or future/today start_time
        }
        // If pastFilter is 'show', show all fixtures regardless of date

        // Upload filter - check the first match's upload status
        if (uploadFilter && fixture.matches && fixture.matches.length > 0) {
            if (fixture.matches[0].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');
    const existingRows = Array.from(tbody.children);
    
    // Create a map of existing fixtures for comparison
    const existingFixtures = new Map();
    existingRows.forEach(row => {
        const fixtureId = row.getAttribute('data-fixture-id');
        if (fixtureId) {
            existingFixtures.set(fixtureId, row);
        }
    });
    
    // Track which fixtures we've processed
    const processedFixtures = new Set();
    
    fixtures.forEach((fixture, index) => {
        const fixtureId = fixture.fixture_id.toString();
        processedFixtures.add(fixtureId);
        
        const startTimeDisplay = fixture.start_time ? new Date(fixture.start_time).toLocaleString() : 'Not set';
        const newRowHTML = `
            <td>
                <strong>#` + fixture.match_number + `</strong>
                <br>
                <small class="text-muted">` + fixture.match_count + ` matches</small>
            </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>` + getFixtureStatusBadge(fixture) + `</td>
            <td>` + getUploadStatusBadge(fixture) + `</td>
            <td>
                <small class="text-info">` + startTimeDisplay + `</small>
            </td>
            <td>
                <small class="text-muted">
                    ` + new Date(fixture.created_at).toLocaleString() + `
                </small>
            </td>
            <td>
                <a href="/fixtures/` + fixture.fixture_id + `" class="btn btn-sm btn-outline-primary">
                    <i class="fas fa-eye me-1"></i>Details
                </a>
            </td>
        `;
        
        const existingRow = existingFixtures.get(fixtureId);
        if (existingRow) {
            // Update existing row only if content has changed
            if (existingRow.innerHTML !== newRowHTML) {
                existingRow.innerHTML = newRowHTML;
                existingRow.style.backgroundColor = '#fff3cd'; // Highlight changed row briefly
                setTimeout(() => {
                    existingRow.style.backgroundColor = '';
                }, 1000);
            }
        } else {
            // Add new row
            const row = document.createElement('tr');
            row.setAttribute('data-fixture-id', fixtureId);
            row.innerHTML = newRowHTML;
            row.style.backgroundColor = '#d4edda'; // Highlight new row briefly
            tbody.appendChild(row);
            setTimeout(() => {
                row.style.backgroundColor = '';
            }, 1000);
        }
    });
    
    // Remove rows that are no longer in the data
    existingFixtures.forEach((row, fixtureId) => {
        if (!processedFixtures.has(fixtureId)) {
            row.style.backgroundColor = '#f8d7da'; // Highlight removed row briefly
            setTimeout(() => {
                if (row.parentNode) {
                    row.parentNode.removeChild(row);
                }
            }, 500);
        }
    });
}

function getFixtureStatusBadge(fixture) {
    const status = fixture.fixture_status;

    switch (status) {
        case 'pending':
            return '<span class="badge bg-warning"><i class="fas fa-clock me-1"></i>Pending</span>';
        case 'running':
            return '<span class="badge bg-info"><i class="fas fa-play me-1"></i>Running</span>';
        case 'scheduled':
            return '<span class="badge bg-secondary"><i class="fas fa-calendar me-1"></i>Scheduled</span>';
        case 'bet':
            return '<span class="badge bg-primary"><i class="fas fa-money-bill me-1"></i>Bet</span>';
        case 'ingame':
            return '<span class="badge bg-success"><i class="fas fa-gamepad me-1"></i>In Game</span>';
        case 'end':
            return '<span class="badge bg-dark"><i class="fas fa-stop me-1"></i>End</span>';
        default:
            return '<span class="badge bg-secondary"><i class="fas fa-question me-1"></i>Unknown</span>';
    }
}

function getUploadStatusBadge(fixture) {
    // Get upload status from the first match in the fixture
    if (!fixture.matches || fixture.matches.length === 0) {
        return '<span class="badge bg-secondary"><i class="fas fa-clock me-1"></i>Pending</span>';
    }

    const firstMatch = fixture.matches[0];
    const status = firstMatch.zip_upload_status || 'pending';
    const progress = firstMatch.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 %}