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

            <div class="d-flex justify-content-between align-items-center mb-4">
                <div>
                    <h1><i class="fas fa-boxing-glove me-2"></i>Match Template Details</h1>
                    <p class="mb-0 text-muted">Edit odds for this match template</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 template 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>
            
            <!-- Success Message -->
            <div id="success-message" class="alert alert-success" style="display: none;">
                <i class="fas fa-check-circle me-2"></i>
                <span id="success-text"></span>
            </div>
            
            <!-- Template Details Content -->
            <div id="template-content" style="display: none;">
                <!-- Template 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>Template Information</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-4">
                                        <table class="table table-borderless">
                                            <tr>
                                                <td><strong>Template ID:</strong></td>
                                                <td><span class="badge bg-primary fs-6" id="template-id"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Fixture ID:</strong></td>
                                                <td><span class="badge bg-secondary fs-6" id="fixture-id"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Match #:</strong></td>
                                                <td><span class="fw-bold" id="match-number"></span></td>
                                            </tr>
                                        </table>
                                    </div>
                                    <div class="col-md-4">
                                        <table class="table table-borderless">
                                            <tr>
                                                <td><strong>Fighter 1:</strong></td>
                                                <td><span id="fighter1"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Fighter 2:</strong></td>
                                                <td><span id="fighter2"></span></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Venue:</strong></td>
                                                <td><span id="venue"></span></td>
                                            </tr>
                                        </table>
                                    </div>
                                    <div class="col-md-4">
                                        <table class="table table-borderless">
                                            <tr>
                                                <td><strong>Created:</strong></td>
                                                <td><small class="text-muted" id="created-at"></small></td>
                                            </tr>
                                            <tr>
                                                <td><strong>Outcomes:</strong></td>
                                                <td><span class="badge bg-info" id="outcome-count"></span></td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Edit Odds Card -->
                <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-edit me-2"></i>Edit Odds</h5>
                                <button id="save-odds-btn" class="btn btn-primary" onclick="saveOdds()">
                                    <i class="fas fa-save me-1"></i>Save Odds
                                </button>
                            </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>This template has no outcomes to edit.</p>
                                </div>
                                
                                <div id="odds-form-container" style="display: none;">
                                    <form id="odds-form">
                                        <div class="table-responsive">
                                            <table class="table table-hover">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th>Outcome ID</th>
                                                        <th>Column Name</th>
                                                        <th>Current Odds</th>
                                                        <th>New Odds</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="outcomes-tbody">
                                                    <!-- Outcomes will be loaded here -->
                                                </tbody>
                                            </table>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script id="template-config" type="application/json">
{
    "templateId": {{ template_id | tojson }}
}
</script>

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

let cachedTemplateData = null;
let isInitialLoad = true;

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

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

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

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

                if (isInitialLoad) {
                    renderTemplateDetails(data.template);
                    content.style.display = 'block';
                } else {
                    updateTemplateDetails(data.template);
                }
            } else {
                if (isInitialLoad) {
                    showError(data.error || 'Failed to load template 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';
    document.getElementById('success-message').style.display = 'none';
}

function showSuccess(message) {
    document.getElementById('success-text').textContent = message;
    document.getElementById('success-message').style.display = 'block';
    document.getElementById('error-message').style.display = 'none';
    
    // Hide success message after 3 seconds
    setTimeout(() => {
        document.getElementById('success-message').style.display = 'none';
    }, 3000);
}

function renderTemplateDetails(template) {
    // Basic template information
    document.getElementById('template-id').textContent = template.id;
    document.getElementById('fixture-id').textContent = template.fixture_id;
    document.getElementById('match-number').textContent = '#' + template.match_number;
    document.getElementById('fighter1').textContent = template.fighter1_township;
    document.getElementById('fighter2').textContent = template.fighter2_township;
    document.getElementById('venue').textContent = template.venue_kampala_township;
    document.getElementById('created-at').textContent = new Date(template.created_at).toLocaleString();
    document.getElementById('outcome-count').textContent = template.outcome_count + ' outcomes';

    // Render outcomes table
    renderOutcomesTable(template.outcomes);
}

function updateTemplateDetails(template) {
    // Update outcome count if changed
    const outcomeCountEl = document.getElementById('outcome-count');
    const newOutcomeCount = template.outcome_count + ' outcomes';
    if (outcomeCountEl.textContent !== newOutcomeCount) {
        outcomeCountEl.textContent = newOutcomeCount;
    }

    // Update outcomes table
    renderOutcomesTable(template.outcomes);
}

function renderOutcomesTable(outcomes) {
    const tbody = document.getElementById('outcomes-tbody');
    const noOutcomes = document.getElementById('no-outcomes');
    const oddsFormContainer = document.getElementById('odds-form-container');

    if (!outcomes || outcomes.length === 0) {
        noOutcomes.style.display = 'block';
        oddsFormContainer.style.display = 'none';
        return;
    }

    noOutcomes.style.display = 'none';
    oddsFormContainer.style.display = 'block';

    tbody.innerHTML = '';
    outcomes.forEach(outcome => {
        const row = document.createElement('tr');
        const oddsValue = outcome.odds !== undefined && outcome.odds !== null ? outcome.odds : 0.0;
        row.innerHTML = `
            <td><span class="badge bg-secondary">${outcome.id}</span></td>
            <td><strong>${outcome.column_name}</strong></td>
            <td><span class="badge bg-info">${oddsValue.toFixed(2)}</span></td>
            <td>
                <input type="number"
                       class="form-control form-control-sm"
                       id="odds-${outcome.id}"
                       value="${oddsValue.toFixed(2)}"
                       step="0.01"
                       min="0"
                       style="width: 120px;">
            </td>
        `;
        tbody.appendChild(row);
    });
}

function saveOdds() {
    const saveBtn = document.getElementById('save-odds-btn');
    const tbody = document.getElementById('outcomes-tbody');
    const rows = tbody.querySelectorAll('tr');
    
    const oddsUpdates = [];
    
    rows.forEach(row => {
        const input = row.querySelector('input[type="number"]');
        if (input) {
            const outcomeId = parseInt(input.id.replace('odds-', ''));
            const newOdds = parseFloat(input.value);
            
            if (!isNaN(newOdds) && newOdds >= 0) {
                oddsUpdates.push({
                    outcome_id: outcomeId,
                    odds: newOdds
                });
            }
        }
    });

    if (oddsUpdates.length === 0) {
        showError('No valid odds to update');
        return;
    }

    // Disable save button and show loading state
    saveBtn.disabled = true;
    saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Saving...';

    fetch(`/api/matches-templates/${templateId}/odds`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            odds: oddsUpdates
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showSuccess(data.message || 'Odds updated successfully');
            // Reload template details to show updated odds
            loadTemplateDetails();
        } else {
            showError(data.error || 'Failed to update odds');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showError('Network error: ' + error.message);
    })
    .finally(() => {
        // Re-enable save button
        saveBtn.disabled = false;
        saveBtn.innerHTML = '<i class="fas fa-save me-1"></i>Save Odds';
    });
}
</script>
{% endblock %}