{% extends "base.html" %}

{% block content %}
<div class="row">
    <div class="col-12">
        <h1 class="mb-4">
            <i class="fas fa-tachometer-alt me-2"></i>Dashboard
            <small class="text-muted">Welcome, {{ current_user.username }}</small>
        </h1>
    </div>
</div>


<!-- Quick Actions -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-bolt me-2"></i>Quick Actions
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <button class="btn btn-outline-primary w-100" id="btn-play-video">
                            <i class="fas fa-play me-2"></i>Start Video Playback
                        </button>
                    </div>
                    <div class="col-md-4 mb-3">
                        <button class="btn btn-outline-success w-100" id="btn-update-overlay">
                            <i class="fas fa-edit me-2"></i>Update Overlay
                        </button>
                    </div>
                    <div class="col-md-4 mb-3">
                        <button class="btn btn-outline-info w-100" id="btn-create-token">
                            <i class="fas fa-plus me-2"></i>Create API Token
                        </button>
                    </div>
                </div>
                
                {% if current_user.is_admin %}
                <!-- Admin Only Actions -->
                <div class="row mt-3 pt-3 border-top">
                    <div class="col-12">
                        <h6 class="text-muted mb-3">
                            <i class="fas fa-shield-alt me-2"></i>Administrator Actions
                        </h6>
                    </div>
                    <div class="col-md-6 mb-3">
                        <button class="btn btn-outline-danger w-100" id="btn-shutdown-app">
                            <i class="fas fa-power-off me-2"></i>Shutdown Application
                        </button>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- Recent Activity & System Info -->
<div class="row">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">
                    <i class="fas fa-clock me-2"></i>Recent Activity
                </h5>
                <small class="text-muted">Last 24 hours</small>
            </div>
            <div class="card-body">
                <div id="activity-list">
                    <div class="d-flex align-items-center mb-3">
                        <div class="flex-shrink-0">
                            <i class="fas fa-info-circle text-info"></i>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <div class="fw-bold">System Started</div>
                            <small class="text-muted">Web dashboard initialized successfully</small>
                        </div>
                        <div class="flex-shrink-0">
                            <small class="text-muted">Just now</small>
                        </div>
                    </div>
                    
                    <div class="d-flex align-items-center mb-3">
                        <div class="flex-shrink-0">
                            <i class="fas fa-user text-success"></i>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <div class="fw-bold">User Login</div>
                            <small class="text-muted">{{ current_user.username }} logged in</small>
                        </div>
                        <div class="flex-shrink-0">
                            <small class="text-muted">Just now</small>
                        </div>
                    </div>
                    
                    <div class="text-center text-muted mt-4">
                        <small>More activity will appear here as you use the system</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-info-circle me-2"></i>System Information
                </h5>
            </div>
            <div class="card-body">
                <dl class="mb-0">
                    <dt class="text-muted">Version</dt>
                    <dd>{{ app_version }}</dd>
                    
                    <dt class="text-muted">Uptime</dt>
                    <dd id="system-uptime">Just started</dd>
                    
                    <dt class="text-muted">User Role</dt>
                    <dd>
                        {% if current_user.is_admin %}
                            <span class="badge bg-danger">Administrator</span>
                        {% else %}
                            <span class="badge bg-primary">User</span>
                        {% endif %}
                    </dd>
                    
                    <dt class="text-muted">Components</dt>
                    <dd>
                        <span class="badge bg-success me-1">Web</span>
                        <span class="badge bg-secondary me-1" id="player-badge">Player</span>
                        <span class="badge bg-secondary" id="api-badge">API Client</span>
                    </dd>
                </dl>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-chart-line me-2"></i>Quick Stats
                </h5>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6">
                        <h4 class="text-primary" id="videos-played">0</h4>
                        <small class="text-muted">Videos Played</small>
                    </div>
                    <div class="col-6">
                        <h4 class="text-success" id="overlays-updated">0</h4>
                        <small class="text-muted">Overlays Updated</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Quick Action Modals -->
<div class="modal fade" id="playVideoModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Start Video Playback</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="play-video-form">
                    <div class="mb-3">
                        <label class="form-label">Video File Path</label>
                        <input type="text" class="form-control" id="video-file-path" 
                               placeholder="/path/to/video.mp4">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Template</label>
                        <select class="form-select" id="video-template">
                            <option value="">Loading templates...</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="confirm-play-video">
                    <i class="fas fa-play me-1"></i>Start Playback
                </button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="updateOverlayModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Update Overlay</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="update-overlay-form">
                    <div class="mb-3">
                        <label class="form-label">Template</label>
                        <select class="form-select" id="overlay-template">
                            <option value="">Loading templates...</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Headline/Title</label>
                        <input type="text" class="form-control" id="overlay-headline" 
                               placeholder="Breaking News">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Text Content</label>
                        <textarea class="form-control" id="overlay-text" rows="3" 
                                  placeholder="Additional information..."></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" id="confirm-update-overlay">
                    <i class="fas fa-edit me-1"></i>Update Overlay
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Load available templates on page load
    loadAvailableTemplates();
    
    // Quick action buttons
    document.getElementById('btn-play-video').addEventListener('click', function() {
        new bootstrap.Modal(document.getElementById('playVideoModal')).show();
    });
    
    document.getElementById('btn-update-overlay').addEventListener('click', function() {
        new bootstrap.Modal(document.getElementById('updateOverlayModal')).show();
    });
    
    document.getElementById('btn-create-token').addEventListener('click', function() {
        window.location.href = '/tokens';
    });
    
    // Admin shutdown button (only exists if user is admin)
    const shutdownBtn = document.getElementById('btn-shutdown-app');
    if (shutdownBtn) {
        shutdownBtn.addEventListener('click', function() {
            if (confirm('Are you sure you want to shutdown the entire application? This will close the Qt player and stop all services.')) {
                fetch('/api/system/shutdown', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Application shutdown initiated. The window will close automatically.');
                        // Redirect to a goodbye page or show shutdown message
                        document.body.innerHTML = '<div class="container mt-5 text-center"><h2>Application Shutting Down...</h2><p>Please wait while the system shuts down gracefully.</p></div>';
                    } else {
                        alert('Failed to shutdown application: ' + (data.error || 'Unknown error'));
                    }
                })
                .catch(error => {
                    alert('Error requesting shutdown: ' + error.message);
                });
            }
        });
    }
    
    // Confirm actions
    document.getElementById('confirm-play-video').addEventListener('click', function() {
        const filePath = document.getElementById('video-file-path').value;
        const template = document.getElementById('video-template').value;
        
        if (!filePath) {
            alert('Please enter a video file path');
            return;
        }
        
        fetch('/api/video/control', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                action: 'play',
                file_path: filePath,
                template: template
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                bootstrap.Modal.getInstance(document.getElementById('playVideoModal')).hide();
                updateVideoStatus();
            } else {
                alert('Failed to start video: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            alert('Error: ' + error.message);
        });
    });
    
    document.getElementById('confirm-update-overlay').addEventListener('click', function() {
        const template = document.getElementById('overlay-template').value;
        const headline = document.getElementById('overlay-headline').value;
        const text = document.getElementById('overlay-text').value;
        
        fetch('/api/overlay', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                template: template,
                data: {
                    headline: headline,
                    ticker_text: text,
                    title: headline,
                    text: text
                }
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                bootstrap.Modal.getInstance(document.getElementById('updateOverlayModal')).hide();
                document.getElementById('overlays-updated').textContent = 
                    parseInt(document.getElementById('overlays-updated').textContent) + 1;
            } else {
                alert('Failed to update overlay: ' + (data.error || 'Unknown error'));
            }
        })
        .catch(error => {
            alert('Error: ' + error.message);
        });
    });
    
    // Status update functions
    function updateSystemStatus() {
        fetch('/api/status')
        .then(response => response.json())
        .then(data => {
            if (data.status === 'online') {
                document.getElementById('system-status-text').textContent = 'Online';
                document.getElementById('system-status').className = 'badge bg-success';
            } else {
                document.getElementById('system-status-text').textContent = 'Error';
                document.getElementById('system-status').className = 'badge bg-danger';
            }
        })
        .catch(error => {
            document.getElementById('system-status-text').textContent = 'Offline';
            document.getElementById('system-status').className = 'badge bg-danger';
        });
    }
    
    function updateVideoStatus() {
        fetch('/api/video/status')
        .then(response => response.json())
        .then(data => {
            const status = data.player_status || 'unknown';
            document.getElementById('video-status-text').textContent = 
                status.charAt(0).toUpperCase() + status.slice(1);
            
            const badge = document.getElementById('player-badge');
            if (status === 'playing') {
                badge.className = 'badge bg-success me-1';
            } else if (status === 'paused') {
                badge.className = 'badge bg-warning me-1';
            } else {
                badge.className = 'badge bg-secondary me-1';
            }
        })
        .catch(error => {
            document.getElementById('video-status-text').textContent = 'Unknown';
        });
    }
    
    // Initial status update
    updateSystemStatus();
    updateVideoStatus();
    
    // Periodic updates
    setInterval(updateSystemStatus, 30000); // 30 seconds
    setInterval(updateVideoStatus, 10000);  // 10 seconds
});

function loadAvailableTemplates() {
    fetch('/api/templates')
        .then(response => response.json())
        .then(data => {
            const videoTemplateSelect = document.getElementById('video-template');
            const overlayTemplateSelect = document.getElementById('overlay-template');
            
            // Clear loading options
            videoTemplateSelect.innerHTML = '';
            overlayTemplateSelect.innerHTML = '';
            
            if (data.templates && Array.isArray(data.templates)) {
                data.templates.forEach(template => {
                    // Add to video template select
                    const videoOption = document.createElement('option');
                    videoOption.value = template.name;
                    videoOption.textContent = template.display_name || template.name;
                    videoTemplateSelect.appendChild(videoOption);
                    
                    // Add to overlay template select
                    const overlayOption = document.createElement('option');
                    overlayOption.value = template.name;
                    overlayOption.textContent = template.display_name || template.name;
                    overlayTemplateSelect.appendChild(overlayOption);
                });
                
                // Select default template if available
                const defaultVideoOption = videoTemplateSelect.querySelector('option[value="default"]');
                if (defaultVideoOption) {
                    defaultVideoOption.selected = true;
                }
                
                const defaultOverlayOption = overlayTemplateSelect.querySelector('option[value="default"]');
                if (defaultOverlayOption) {
                    defaultOverlayOption.selected = true;
                }
            } else {
                // Fallback if no templates found
                const videoOption = document.createElement('option');
                videoOption.value = 'default';
                videoOption.textContent = 'Default';
                videoTemplateSelect.appendChild(videoOption);
                
                const overlayOption = document.createElement('option');
                overlayOption.value = 'default';
                overlayOption.textContent = 'Default';
                overlayTemplateSelect.appendChild(overlayOption);
            }
        })
        .catch(error => {
            console.error('Error loading templates:', error);
            // Fallback template options
            const videoTemplateSelect = document.getElementById('video-template');
            const overlayTemplateSelect = document.getElementById('overlay-template');
            
            videoTemplateSelect.innerHTML = '<option value="default">Default</option>';
            overlayTemplateSelect.innerHTML = '<option value="default">Default</option>';
        });
}
</script>
{% endblock %}
