{% 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">Fixture Details</li>
                </ol>
            </nav>

            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h1><i class="fas fa-boxing me-2"></i>Fixture Details</h1>
                    <p class="mb-0 text-muted">All matches in this fixture</p>
                </div>
                <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;">
                <!-- Fixture Information Card -->
                <div class="row">
                    <div class="col-12">
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5><i class="fas fa-info-circle me-2"></i>Fixture Information</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-4">
                                        <table class="table table-borderless">
                                            <tr>
                                                <td><strong>Fixture ID:</strong></td>
                                                <td><span class="badge bg-primary fs-6" id="fixture-id"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Status:</strong></td>
                                                <td><span id="fixture-status-badge"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Match Count:</strong></td>
                                                <td><span class="fw-bold" id="match-count"></span></td>
                                            </tr>
                                        </table>
                                    </div>
                                    <div class="col-md-4">
                                        <table class="table table-borderless">
                                            <tr>
                                                <td><strong>Venue:</strong></td>
                                                <td><span id="venue"></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>Created:</strong></td>
                                                <td><small class="text-muted" id="created-at"></small></td>
                                            </tr>
                                        </table>
                                    </div>
                                    <div class="col-md-4">
                                        <table class="table table-borderless">
                                            <tr>
                                                <td><strong>Sample Fighters:</strong></td>
                                                <td><small class="text-muted" id="sample-fighters"></small></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Active Time:</strong></td>
                                                <td><small class="text-muted" id="active-time"></small></td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Matches in Fixture -->
                <div class="row">
                    <div class="col-12">
                        <div class="card mb-4">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5><i class="fas fa-list me-2"></i>Matches in This Fixture</h5>
                                <span id="matches-count" class="badge bg-secondary">0 matches</span>
                            </div>
                            <div class="card-body p-0">
                                <div class="table-responsive">
                                    <table class="table table-hover mb-0">
                                        <thead class="table-light">
                                            <tr>
                                                <th>Match #</th>
                                                <th>Fighters</th>
                                                <th>Status</th>
                                                <th>Start Time</th>
                                                <th>Result</th>
                                                <th>Outcomes</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody id="matches-tbody">
                                            <!-- Matches will be loaded here -->
                                        </tbody>
                                    </table>
                                </div>
                            </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">
                        <!-- Fixture Summary Card -->
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5><i class="fas fa-chart-bar me-2"></i>Fixture Summary</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">Status Distribution</label>
                                    <div id="status-summary">
                                        <!-- Status summary will be populated by JavaScript -->
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">Upload Status</label>
                                    <div id="upload-summary">
                                        <!-- Upload summary will be populated by JavaScript -->
                                    </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>Source File</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>Fixture Timestamps</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-2">
                                    <label class="form-label small">Created</label>
                                    <div class="text-muted small" id="fixture-created-at"></div>
                                </div>
                                <div>
                                    <label class="form-label small">Last Updated</label>
                                    <div class="text-muted small" id="fixture-updated-at"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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

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

let cachedFixtureData = null;
let isInitialLoad = true;

// Load fixture details on page load
document.addEventListener('DOMContentLoaded', function() {
    loadFixtureDetails();
    
    // Set up auto-refresh every 5 seconds
    setInterval(loadFixtureDetails, 5000);
});

function loadFixtureDetails() {
    const loading = document.getElementById('loading');
    const errorMessage = document.getElementById('error-message');
    const content = document.getElementById('fixture-content');

    // Only show loading state on initial load
    if (isInitialLoad) {
        loading.style.display = 'block';
        errorMessage.style.display = 'none';
        content.style.display = 'none';
    }

    fetch(`/api/fixtures/${fixtureId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Check if data has actually changed
                const currentDataString = JSON.stringify(data);
                if (cachedFixtureData === currentDataString && !isInitialLoad) {
                    console.log('📦 No changes in fixture data, skipping update');
                    return;
                }
                cachedFixtureData = currentDataString;

                if (isInitialLoad) {
                    renderFixtureDetails(data.fixture, data.matches);
                    content.style.display = 'block';
                } else {
                    updateFixtureDetails(data.fixture, data.matches);
                }
            } else {
                if (isInitialLoad) {
                    showError(data.error || 'Failed to load fixture details');
                }
            }
        })
        .catch(error => {
            console.error('Error:', error);
            if (isInitialLoad) {
                showError('Network error: ' + error.message);
            }
        })
        .finally(() => {
            if (isInitialLoad) {
                loading.style.display = 'none';
                isInitialLoad = false;
            }
        });
}

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

function renderFixtureDetails(fixture, matches) {
    // Basic fixture information
    document.getElementById('fixture-id').textContent = fixture.fixture_id;
    document.getElementById('fixture-status-badge').innerHTML = getFixtureStatusBadge(fixture);
    document.getElementById('match-count').textContent = fixture.match_count + ' matches';
    document.getElementById('venue').textContent = fixture.venue_kampala_township;

    // Start time
    if (fixture.start_time) {
        document.getElementById('start-time').textContent = new Date(fixture.start_time).toLocaleString();
        document.getElementById('start-time').classList.remove('text-muted');
    }

    // Sample fighters (from first match)
    if (matches.length > 0) {
        const firstMatch = matches[0];
        document.getElementById('sample-fighters').textContent = firstMatch.fighter1_township + ' vs ' + firstMatch.fighter2_township;
    }

    // Active time
    if (fixture.fixture_active_time) {
        document.getElementById('active-time').textContent = new Date(fixture.fixture_active_time * 1000).toLocaleString();
    }

    // File information (from first match)
    if (matches.length > 0) {
        const firstMatch = matches[0];
        document.getElementById('filename').textContent = firstMatch.filename;
        document.getElementById('file-sha1sum').textContent = firstMatch.file_sha1sum;
    }

    // Timestamps
    document.getElementById('created-at').textContent = new Date(fixture.created_at).toLocaleString();
    document.getElementById('fixture-created-at').textContent = new Date(fixture.created_at).toLocaleString();

    // Render matches table
    renderMatchesTable(matches);

    // Render fixture summary
    renderFixtureSummary(matches);
}

function updateFixtureDetails(fixture, matches) {
    // Update fixture information that might have changed
    const statusBadge = document.getElementById('fixture-status-badge');
    const newStatusBadge = getFixtureStatusBadge(fixture);
    if (statusBadge.innerHTML !== newStatusBadge) {
        statusBadge.innerHTML = newStatusBadge;
        statusBadge.style.backgroundColor = '#fff3cd';
        setTimeout(() => {
            statusBadge.style.backgroundColor = '';
        }, 1000);
    }

    // Update match count
    const matchCountEl = document.getElementById('match-count');
    const newMatchCount = fixture.match_count + ' matches';
    if (matchCountEl.textContent !== newMatchCount) {
        matchCountEl.textContent = newMatchCount;
    }

    // Update start time if changed
    if (fixture.start_time) {
        const startTimeEl = document.getElementById('start-time');
        const newStartTime = new Date(fixture.start_time).toLocaleString();
        if (startTimeEl.textContent !== newStartTime) {
            startTimeEl.textContent = newStartTime;
            startTimeEl.classList.remove('text-muted');
        }
    }

    // Update matches table with smooth transitions
    updateMatchesTable(matches);
    
    // Update fixture summary
    renderFixtureSummary(matches);
}

function renderMatchesTable(matches) {
    const tbody = document.getElementById('matches-tbody');
    const matchesCount = document.getElementById('matches-count');

    matchesCount.textContent = matches.length + ' matches';

    tbody.innerHTML = '';
    matches.forEach(match => {
        const row = document.createElement('tr');
        const startTimeDisplay = match.start_time ? new Date(match.start_time).toLocaleString() : 'Not set';
        const resultDisplay = match.result || 'Not available';
        const outcomesCount = match.outcome_count || 0;

        row.innerHTML = `
            <td><strong>#${match.match_number}</strong></td>
            <td>
                <div class="fw-bold">${match.fighter1_township}</div>
                <small class="text-muted">vs</small>
                <div class="fw-bold">${match.fighter2_township}</div>
            </td>
            <td>${getStatusBadge(match)}</td>
            <td><small class="text-info">${startTimeDisplay}</small></td>
            <td><small class="text-muted">${resultDisplay}</small></td>
            <td><span class="badge bg-light text-dark">${outcomesCount} outcomes</span></td>
            <td>
                <a href="/matches/${match.id}/${fixtureId}" class="btn btn-sm btn-outline-primary">
                    <i class="fas fa-eye me-1"></i>View
                </a>
            </td>
        `;
        row.setAttribute('data-match-id', match.id);
        tbody.appendChild(row);
    });
}

function updateMatchesTable(matches) {
    const tbody = document.getElementById('matches-tbody');
    const matchesCount = document.getElementById('matches-count');

    matchesCount.textContent = matches.length + ' matches';

    // Get existing rows
    const existingRows = Array.from(tbody.children);
    const existingMatches = new Map();
    existingRows.forEach(row => {
        const matchId = row.getAttribute('data-match-id');
        if (matchId) {
            existingMatches.set(parseInt(matchId), row);
        }
    });

    const processedMatches = new Set();

    matches.forEach(match => {
        processedMatches.add(match.id);
        
        const startTimeDisplay = match.start_time ? new Date(match.start_time).toLocaleString() : 'Not set';
        const resultDisplay = match.result || 'Not available';
        const outcomesCount = match.outcome_count || 0;

        const newRowHTML = `
            <td><strong>#${match.match_number}</strong></td>
            <td>
                <div class="fw-bold">${match.fighter1_township}</div>
                <small class="text-muted">vs</small>
                <div class="fw-bold">${match.fighter2_township}</div>
            </td>
            <td>${getStatusBadge(match)}</td>
            <td><small class="text-info">${startTimeDisplay}</small></td>
            <td><small class="text-muted">${resultDisplay}</small></td>
            <td><span class="badge bg-light text-dark">${outcomesCount} outcomes</span></td>
            <td>
                <a href="/matches/${match.id}/${fixtureId}" class="btn btn-sm btn-outline-primary">
                    <i class="fas fa-eye me-1"></i>View
                </a>
            </td>
        `;

        const existingRow = existingMatches.get(match.id);
        if (existingRow) {
            // Update existing row only if content changed
            if (existingRow.innerHTML !== newRowHTML) {
                existingRow.innerHTML = newRowHTML;
                existingRow.style.backgroundColor = '#fff3cd'; // Highlight briefly
                setTimeout(() => {
                    existingRow.style.backgroundColor = '';
                }, 1000);
            }
        } else {
            // Add new row
            const row = document.createElement('tr');
            row.setAttribute('data-match-id', match.id);
            row.innerHTML = newRowHTML;
            row.style.backgroundColor = '#d4edda'; // Highlight new row
            tbody.appendChild(row);
            setTimeout(() => {
                row.style.backgroundColor = '';
            }, 1000);
        }
    });

    // Remove rows no longer in data
    existingMatches.forEach((row, matchId) => {
        if (!processedMatches.has(matchId)) {
            row.style.backgroundColor = '#f8d7da'; // Highlight removed row
            setTimeout(() => {
                if (row.parentNode) {
                    row.parentNode.removeChild(row);
                }
            }, 500);
        }
    });
}

function renderFixtureSummary(matches) {
    // Calculate status distribution
    const statusCounts = {};
    const uploadCounts = {};

    matches.forEach(match => {
        // Count statuses
        const status = match.status || 'unknown';
        statusCounts[status] = (statusCounts[status] || 0) + 1;

        // Count upload statuses
        const uploadStatus = match.zip_upload_status || 'pending';
        uploadCounts[uploadStatus] = (uploadCounts[uploadStatus] || 0) + 1;
    });

    // Render status summary
    const statusSummary = document.getElementById('status-summary');
    statusSummary.innerHTML = Object.entries(statusCounts)
        .map(([status, count]) => `<div class="small"><span class="badge bg-secondary">${status}</span> ${count}</div>`)
        .join('');

    // Render upload summary
    const uploadSummary = document.getElementById('upload-summary');
    uploadSummary.innerHTML = Object.entries(uploadCounts)
        .map(([status, count]) => `<div class="small"><span class="badge bg-light text-dark">${status}</span> ${count}</div>`)
        .join('');
}


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 getStatusBadge(match) {
    const status = match.status;

    switch (status) {
        case 'pending':
            return '<span class="badge bg-warning"><i class="fas fa-clock me-1"></i>Pending</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>';
        case 'cancelled':
            return '<span class="badge bg-danger"><i class="fas fa-times me-1"></i>Cancelled</span>';
        case 'failed':
            return '<span class="badge bg-danger"><i class="fas fa-exclamation-triangle me-1"></i>Failed</span>';
        case 'paused':
            return '<span class="badge bg-warning"><i class="fas fa-pause me-1"></i>Paused</span>';
        default:
            return '<span class="badge bg-secondary"><i class="fas fa-question me-1"></i>Unknown</span>';
    }
}

function getUploadStatusBadge(match) {
    const status = match.zip_upload_status || 'pending';
    const progress = match.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 %}