{% extends "base.html" %}

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

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <!-- Navigation -->
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ url_for('main.fixtures') }}">Fixtures</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Match Details</li>
                </ol>
            </nav>
            
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1><i class="fas fa-boxing me-2"></i>Fixture Details</h1>
                <a href="{{ url_for('main.fixtures') }}" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-1"></i>Back to Fixtures
                </a>
            </div>
            
            <!-- Loading Spinner -->
            <div id="loading" class="text-center my-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
                <p class="mt-2">Loading fixture details...</p>
            </div>
            
            <!-- Error Message -->
            <div id="error-message" class="alert alert-danger" style="display: none;">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <span id="error-text"></span>
            </div>
            
            <!-- Fixture Details Content -->
            <div id="fixture-content" style="display: none;">
                <!-- Match Information Card -->
                <div class="row">
                    <div class="col-lg-8">
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5><i class="fas fa-info-circle me-2"></i>Match Information</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <table class="table table-borderless">
                                            <tr>
                                                <td><strong>Match Number:</strong></td>
                                                <td><span class="badge bg-primary fs-6" id="match-number"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Fighter 1:</strong></td>
                                                <td><span class="fw-bold text-primary" id="fighter1"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Fighter 2:</strong></td>
                                                <td><span class="fw-bold text-primary" id="fighter2"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Venue:</strong></td>
                                                <td><span id="venue"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Fixture ID:</strong></td>
                                                <td><small class="text-muted" id="fixture-id"></small></td>
                                            </tr>
                                        </table>
                                    </div>
                                    <div class="col-md-6">
                                        <table class="table table-borderless">
                                            <tr>
                                                <td><strong>Status:</strong></td>
                                                <td><span id="status-badge"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Active:</strong></td>
                                                <td><span id="active-status"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Start Time:</strong></td>
                                                <td><span id="start-time" class="text-muted">Not set</span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>End Time:</strong></td>
                                                <td><span id="end-time" class="text-muted">Not set</span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Result:</strong></td>
                                                <td><span id="result" class="text-muted">Not available</span></td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Match Outcomes Card -->
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5><i class="fas fa-chart-line me-2"></i>Match Outcomes</h5>
                                <span id="outcomes-count" class="badge bg-secondary">0 outcomes</span>
                            </div>
                            <div class="card-body">
                                <div id="no-outcomes" class="text-center text-muted py-4">
                                    <i class="fas fa-chart-line fa-3x mb-3"></i>
                                    <h5>No Outcomes Available</h5>
                                    <p>No outcome data has been synchronized for this match yet.</p>
                                </div>
                                
                                <div id="outcomes-table-container" style="display: none;">
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Column Name</th>
                                                    <th>Value</th>
                                                    <th>Updated</th>
                                                </tr>
                                            </thead>
                                            <tbody id="outcomes-tbody">
                                                <!-- Outcomes will be loaded here -->
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Side Panel -->
                    <div class="col-lg-4">
                        <!-- Upload Status Card -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5><i class="fas fa-cloud-upload-alt me-2"></i>Upload Status</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">ZIP Upload Status</label>
                                    <div id="upload-status-badge"></div>
                                </div>
                                
                                <div class="mb-3" id="progress-container" style="display: none;">
                                    <label class="form-label">Upload Progress</label>
                                    <div class="progress">
                                        <div class="progress-bar" role="progressbar" id="progress-bar" style="width: 0%">0%</div>
                                    </div>
                                </div>
                                
                                <div class="mb-3" id="zip-file-info" style="display: none;">
                                    <label class="form-label">ZIP File</label>
                                    <div class="small text-muted">
                                        <div><strong>Filename:</strong> <span id="zip-filename"></span></div>
                                        <div><strong>SHA1:</strong> <span id="zip-sha1sum" class="font-monospace"></span></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- File Information Card -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5><i class="fas fa-file me-2"></i>File Information</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">Fixture File</label>
                                    <div class="small text-muted">
                                        <div><strong>Filename:</strong> <span id="filename"></span></div>
                                        <div><strong>SHA1:</strong> <span id="file-sha1sum" class="font-monospace"></span></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Timestamps Card -->
                        <div class="card">
                            <div class="card-header">
                                <h5><i class="fas fa-clock me-2"></i>Timestamps</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-2">
                                    <label class="form-label small">Created</label>
                                    <div class="text-muted small" id="created-at"></div>
                                </div>
                                <div>
                                    <label class="form-label small">Last Updated</label>
                                    <div class="text-muted small" id="updated-at"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script id="fixture-config" type="application/json">
{
    "matchId": {{ match_id | tojson }}
}
</script>

<script>
const config = JSON.parse(document.getElementById('fixture-config').textContent);
const matchId = config.matchId;

// Load fixture details on page load
document.addEventListener('DOMContentLoaded', function() {
    loadFixtureDetails();
});

function loadFixtureDetails() {
    const loading = document.getElementById('loading');
    const errorMessage = document.getElementById('error-message');
    const content = document.getElementById('fixture-content');
    
    loading.style.display = 'block';
    errorMessage.style.display = 'none';
    content.style.display = 'none';
    
    fetch(`/api/fixtures/${matchId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                renderFixtureDetails(data.match);
                content.style.display = 'block';
            } else {
                showError(data.error || 'Failed to load fixture details');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showError('Network error: ' + error.message);
        })
        .finally(() => {
            loading.style.display = 'none';
        });
}

function showError(message) {
    document.getElementById('error-text').textContent = message;
    document.getElementById('error-message').style.display = 'block';
}

function renderFixtureDetails(match) {
    // Basic match information
    document.getElementById('match-number').textContent = '#' + match.match_number;
    document.getElementById('fighter1').textContent = match.fighter1_township;
    document.getElementById('fighter2').textContent = match.fighter2_township;
    document.getElementById('venue').textContent = match.venue_kampala_township;
    document.getElementById('fixture-id').textContent = match.fixture_id;
    
    // Status information
    document.getElementById('status-badge').innerHTML = getStatusBadge(match);
    document.getElementById('active-status').innerHTML = match.active_status 
        ? '<span class="badge bg-success">Active</span>' 
        : '<span class="badge bg-secondary">Inactive</span>';
    
    // Times and result
    if (match.start_time) {
        document.getElementById('start-time').textContent = new Date(match.start_time).toLocaleString();
        document.getElementById('start-time').classList.remove('text-muted');
    }
    
    if (match.end_time) {
        document.getElementById('end-time').textContent = new Date(match.end_time).toLocaleString();
        document.getElementById('end-time').classList.remove('text-muted');
    }
    
    if (match.result) {
        document.getElementById('result').textContent = match.result;
        document.getElementById('result').classList.remove('text-muted');
    }
    
    // File information
    document.getElementById('filename').textContent = match.filename;
    document.getElementById('file-sha1sum').textContent = match.file_sha1sum;
    
    // Upload status
    renderUploadStatus(match);
    
    // Outcomes
    renderOutcomes(match.outcomes || []);
    
    // Timestamps
    document.getElementById('created-at').textContent = new Date(match.created_at).toLocaleString();
    document.getElementById('updated-at').textContent = new Date(match.updated_at).toLocaleString();
}

function renderUploadStatus(match) {
    const uploadBadge = document.getElementById('upload-status-badge');
    const progressContainer = document.getElementById('progress-container');
    const zipFileInfo = document.getElementById('zip-file-info');
    
    uploadBadge.innerHTML = getUploadStatusBadge(match);
    
    // Show progress bar if uploading
    if (match.zip_upload_status === 'uploading') {
        const progress = match.zip_upload_progress || 0;
        const progressBar = document.getElementById('progress-bar');
        progressBar.style.width = progress + '%';
        progressBar.textContent = progress.toFixed(1) + '%';
        progressContainer.style.display = 'block';
    }
    
    // Show ZIP file info if available
    if (match.zip_filename) {
        document.getElementById('zip-filename').textContent = match.zip_filename;
        if (match.zip_sha1sum) {
            document.getElementById('zip-sha1sum').textContent = match.zip_sha1sum;
        }
        zipFileInfo.style.display = 'block';
    }
}

function renderOutcomes(outcomes) {
    const noOutcomes = document.getElementById('no-outcomes');
    const outcomesContainer = document.getElementById('outcomes-table-container');
    const outcomesCount = document.getElementById('outcomes-count');
    const tbody = document.getElementById('outcomes-tbody');
    
    outcomesCount.textContent = outcomes.length + ' outcomes';
    
    if (outcomes.length === 0) {
        noOutcomes.style.display = 'block';
        outcomesContainer.style.display = 'none';
        return;
    }
    
    noOutcomes.style.display = 'none';
    outcomesContainer.style.display = 'block';
    
    tbody.innerHTML = '';
    outcomes.forEach(outcome => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td><span class="badge bg-light text-dark">${outcome.column_name}</span></td>
            <td><strong class="text-primary">${outcome.float_value}</strong></td>
            <td><small class="text-muted">${new Date(outcome.updated_at).toLocaleString()}</small></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>';
    }
}
</script>
{% endblock %}