{% 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 Template</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>Fixture Template</h1>
                    <p class="mb-0 text-muted">All matches in the fixture 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 matches...</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>
            
            <!-- 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 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>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>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Matches in Template -->
                <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 Template</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>Outcomes</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody id="matches-tbody">
                                            <!-- Matches will be loaded here -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let cachedTemplateData = null;
let isInitialLoad = true;

// Load template details on page load
document.addEventListener('DOMContentLoaded', function() {
    loadTemplateDetails();
    
    // Set up auto-refresh every 15 seconds
    setInterval(loadTemplateDetails, 15000);
});

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')
        .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;

                // Get the first template from the templates array
                const template = data.templates && data.templates.length > 0 ? data.templates[0] : null;
                
                if (!template) {
                    if (isInitialLoad) {
                        showError('No template data available');
                    }
                    return;
                }

                if (isInitialLoad) {
                    renderTemplateDetails(template);
                    content.style.display = 'block';
                } else {
                    updateTemplateDetails(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';
}

function renderTemplateDetails(template) {
    // Safety check for template object
    if (!template) {
        showError('Template data is not available');
        return;
    }

    // Basic template information
    document.getElementById('template-id').textContent = template.id || 'N/A';
    document.getElementById('fixture-id').textContent = template.fixture_id || 'N/A';
    document.getElementById('match-count').textContent = (template.match_count || 0) + ' matches';
    document.getElementById('venue').textContent = template.venue_kampala_township || 'N/A';
    document.getElementById('created-at').textContent = template.created_at ? new Date(template.created_at).toLocaleString() : 'N/A';

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

    // Render matches table
    renderMatchesTable(template.matches || []);
}

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

    // Update matches table with smooth transitions
    updateMatchesTable(template.matches || []);
}

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

    if (!matches || !Array.isArray(matches)) {
        matchesCount.textContent = '0 matches';
        tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">No matches available</td></tr>';
        return;
    }

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

    tbody.innerHTML = '';
    matches.forEach(match => {
        if (!match || !match.id) {
            console.warn('Invalid match data:', match);
            return;
        }

        const row = document.createElement('tr');
        const outcomesCount = match.outcome_count || 0;

        row.innerHTML = `
            <td><strong>#${match.match_number || 'N/A'}</strong></td>
            <td>
                <div class="fw-bold">${match.fighter1_township || 'Unknown'}</div>
                <small class="text-muted">vs</small>
                <div class="fw-bold">${match.fighter2_township || 'Unknown'}</div>
            </td>
            <td>${getStatusBadge(match)}</td>
            <td><span class="badge bg-light text-dark">${outcomesCount} outcomes</span></td>
            <td>
                <a href="/matches-templates/${match.id}" 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 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><span class="badge bg-light text-dark">${outcomesCount} outcomes</span></td>
            <td>
                <a href="/matches-templates/${match.id}" 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 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>';
    }
}
</script>
{% endblock %}