{% 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"><a href="#" onclick="goBackToFixture()">Fixture Details</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">
                <div>
                    <h1><i class="fas fa-boxing me-2"></i>Match Details</h1>
                    <p class="mb-0 text-muted">Complete match information, outcomes, and results</p>
                </div>
                <a href="javascript:history.back()" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-1"></i>Back
                </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 match 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>

            <!-- Match Details Content -->
            <div id="match-content" style="display: none;">
                <!-- Match 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>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 #:</strong></td>
                                                <td><span class="badge bg-primary fs-6" id="match-number"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Status:</strong></td>
                                                <td><span id="match-status-badge"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Fighters:</strong></td>
                                                <td><span id="fighters"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Venue:</strong></td>
                                                <td><span id="venue"></span></td>
                                            </tr>
                                        </table>
                                    </div>
                                    <div class="col-md-6">
                                        <table class="table table-borderless">
                                            <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>
                                            <tr id="winning-outcomes-row" style="display: none;">
                                                <td><strong>Winning Outcomes:</strong></td>
                                                <td><span id="winning-outcomes" class="badge bg-success"></span></td>
                                            </tr>
                                            <tr id="under-over-row" style="display: none;">
                                                <td><strong>Under/Over:</strong></td>
                                                <td><span id="under-over-result" class="badge bg-info"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Fixture ID:</strong></td>
                                                <td><small class="text-muted" id="fixture-id"></small></td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Match Outcomes -->
                <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-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" style="display: none;">
                                    <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-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>
                </div>

                <!-- File Information -->
                <div class="row">
                    <div class="col-md-6">
                        <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>
                    </div>
                    <div class="col-md-6">
                        <div class="card mb-4">
                            <div class="card-header">
                                <h5><i class="fas fa-upload me-2"></i>Upload Status</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">ZIP Upload</label>
                                    <div id="upload-status"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Timestamps -->
                <div class="row">
                    <div class="col-12">
                        <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="row">
                                    <div class="col-md-4">
                                        <label class="form-label small">Created</label>
                                        <div class="text-muted small" id="created-at"></div>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label small">Updated</label>
                                        <div class="text-muted small" id="updated-at"></div>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label small">Active Time</label>
                                        <div class="text-muted small" id="active-time"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script id="match-config" type="application/json">
{
    "matchId": {{ match_id | tojson }},
    "fixtureId": {{ fixture_id | tojson }}
}
</script>

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

let cachedMatchData = null;
let isInitialLoad = true;

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

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

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

    // First get fixture details to get all matches, then find the specific match
    fetch(`/api/fixtures/${fixtureId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Find the specific match within the fixture
                const match = data.matches.find(m => m.id === matchId);
                if (match) {
                    // Check if data has actually changed
                    const currentMatchString = JSON.stringify(match);
                    if (cachedMatchData === currentMatchString && !isInitialLoad) {
                        console.log('📦 No changes in match data, skipping update');
                        return;
                    }
                    cachedMatchData = currentMatchString;

                    if (isInitialLoad) {
                        renderMatchDetails(match);
                        content.style.display = 'block';
                    } else {
                        updateMatchDetails(match);
                    }
                } else {
                    if (isInitialLoad) {
                        showError('Match not found in fixture');
                    }
                }
            } 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 formatWinningOutcomes(winningOutcomes) {
    // Safely format winning outcomes, handling cases where it's not an array
    let outcomesArray = [];

    if (Array.isArray(winningOutcomes) && winningOutcomes.length > 0) {
        outcomesArray = winningOutcomes;
    } else if (winningOutcomes && typeof winningOutcomes === 'string') {
        // Try to parse JSON string
        try {
            const parsed = JSON.parse(winningOutcomes);
            if (Array.isArray(parsed) && parsed.length > 0) {
                outcomesArray = parsed;
            } else {
                return winningOutcomes; // Return original string if not a valid array
            }
        } catch (e) {
            return winningOutcomes; // Return original string if parsing fails
        }
    } else if (winningOutcomes && typeof winningOutcomes === 'object') {
        // If it's an object, try to stringify it
        return JSON.stringify(winningOutcomes);
    } else {
        return '';
    }

    return outcomesArray.join(', ');
}

function updateMatchDetails(match) {
    // Update status badge with highlighting
    const statusBadge = document.getElementById('match-status-badge');
    const newStatusBadge = getStatusBadge(match);
    if (statusBadge.innerHTML !== newStatusBadge) {
        statusBadge.innerHTML = newStatusBadge;
        statusBadge.style.backgroundColor = '#fff3cd';
        setTimeout(() => {
            statusBadge.style.backgroundColor = '';
        }, 1000);
    }

    // Update start time if changed
    if (match.start_time) {
        const startTimeEl = document.getElementById('start-time');
        const newStartTime = new Date(match.start_time).toLocaleString();
        if (startTimeEl.textContent !== newStartTime) {
            startTimeEl.textContent = newStartTime;
            startTimeEl.classList.remove('text-muted');
            startTimeEl.style.backgroundColor = '#fff3cd';
            setTimeout(() => {
                startTimeEl.style.backgroundColor = '';
            }, 1000);
        }
    }

    // Update end time if changed
    if (match.end_time) {
        const endTimeEl = document.getElementById('end-time');
        const newEndTime = new Date(match.end_time).toLocaleString();
        if (endTimeEl.textContent !== newEndTime) {
            endTimeEl.textContent = newEndTime;
            endTimeEl.classList.remove('text-muted');
            endTimeEl.style.backgroundColor = '#fff3cd';
            setTimeout(() => {
                endTimeEl.style.backgroundColor = '';
            }, 1000);
        }
    }

    // Update result if changed
    if (match.result) {
        const resultEl = document.getElementById('result');
        if (resultEl.textContent !== match.result) {
            resultEl.textContent = match.result;
            resultEl.classList.remove('text-muted');
            resultEl.style.backgroundColor = '#fff3cd';
            setTimeout(() => {
                resultEl.style.backgroundColor = '';
            }, 1000);
        }
    }

    // Update winning outcomes if changed
    const winningOutcomesRow = document.getElementById('winning-outcomes-row');
    const winningOutcomesEl = document.getElementById('winning-outcomes');
    const currentWinningOutcomes = formatWinningOutcomes(match.winning_outcomes);

    if (currentWinningOutcomes !== winningOutcomesEl.textContent) {
        if (currentWinningOutcomes) {
            winningOutcomesEl.textContent = currentWinningOutcomes;
            winningOutcomesRow.style.display = 'table-row';
            winningOutcomesEl.style.backgroundColor = '#d1ecf1';
            setTimeout(() => {
                winningOutcomesEl.style.backgroundColor = '';
            }, 1000);
        } else {
            winningOutcomesRow.style.display = 'none';
        }
    }

    // Update under/over result if changed
    const underOverRow = document.getElementById('under-over-row');
    const underOverEl = document.getElementById('under-over-result');
    const currentUnderOver = match.under_over_result || '';

    if (currentUnderOver !== underOverEl.textContent) {
        if (currentUnderOver) {
            underOverEl.textContent = currentUnderOver;
            underOverRow.style.display = 'table-row';
            underOverEl.style.backgroundColor = '#d1ecf1';
            setTimeout(() => {
                underOverEl.style.backgroundColor = '';
            }, 1000);
        } else {
            underOverRow.style.display = 'none';
        }
    }

    // Update upload status
    const uploadStatusEl = document.getElementById('upload-status');
    const newUploadStatus = getUploadStatusBadge(match);
    if (uploadStatusEl.innerHTML !== newUploadStatus) {
        uploadStatusEl.innerHTML = newUploadStatus;
        uploadStatusEl.style.backgroundColor = '#fff3cd';
        setTimeout(() => {
            uploadStatusEl.style.backgroundColor = '';
        }, 1000);
    }

    // Update timestamps
    const updatedAtEl = document.getElementById('updated-at');
    const newUpdatedAt = new Date(match.updated_at).toLocaleString();
    if (updatedAtEl.textContent !== newUpdatedAt) {
        updatedAtEl.textContent = newUpdatedAt;
        updatedAtEl.style.backgroundColor = '#fff3cd';
        setTimeout(() => {
            updatedAtEl.style.backgroundColor = '';
        }, 1000);
    }

    // Update outcomes
    renderOutcomes(match.outcomes || []);
}

function renderMatchDetails(match) {
    // Basic match information
    document.getElementById('match-number').textContent = match.match_number;
    document.getElementById('match-status-badge').innerHTML = getStatusBadge(match);
    document.getElementById('fighters').textContent = match.fighter1_township + ' vs ' + match.fighter2_township;
    document.getElementById('venue').textContent = match.venue_kampala_township;
    document.getElementById('fixture-id').textContent = match.fixture_id;

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

    // End time
    if (match.end_time) {
        document.getElementById('end-time').textContent = new Date(match.end_time).toLocaleString();
        document.getElementById('end-time').classList.remove('text-muted');
    }

    // Result
    if (match.result) {
        document.getElementById('result').textContent = match.result;
        document.getElementById('result').classList.remove('text-muted');
    }

    // Winning outcomes
    const winningOutcomesText = formatWinningOutcomes(match.winning_outcomes);
    if (winningOutcomesText) {
        document.getElementById('winning-outcomes').textContent = winningOutcomesText;
        document.getElementById('winning-outcomes-row').style.display = 'table-row';
    }

    // Under/Over result
    if (match.under_over_result) {
        document.getElementById('under-over-result').textContent = match.under_over_result;
        document.getElementById('under-over-row').style.display = 'table-row';
    }

    // File information
    document.getElementById('filename').textContent = match.filename;
    document.getElementById('file-sha1sum').textContent = match.file_sha1sum;

    // Upload status
    document.getElementById('upload-status').innerHTML = getUploadStatusBadge(match);

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

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

    // Render outcomes
    renderOutcomes(match.outcomes || []);
}

function renderOutcomes(outcomes) {
    const outcomesCount = document.getElementById('outcomes-count');
    const noOutcomes = document.getElementById('no-outcomes');
    const outcomesContainer = document.getElementById('outcomes-container');
    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');
        const updatedTime = new Date(outcome.updated_at).toLocaleString();

        row.innerHTML = `
            <td><strong>${outcome.column_name}</strong></td>
            <td><span class="badge bg-primary">${outcome.float_value}</span></td>
            <td><small class="text-muted">${updatedTime}</small></td>
        `;
        tbody.appendChild(row);
    });
}

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 'done':
            return '<span class="badge bg-dark"><i class="fas fa-stop me-1"></i>Done</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>';
    }
}

function goBackToFixture() {
    // Use the fixture_id from the config
    if (fixtureId) {
        window.location.href = `/fixtures/${fixtureId}`;
    } else {
        // Fallback to browser back
        window.history.back();
    }
}
</script>
{% endblock %}