{% extends "base.html" %}

{% block title %}AtlasServer - {{ application.name }}{% endblock %}
{% block header_title %}Application Details{% endblock %}

{% block content %}
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="mb-6 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
            <div class="flex items-center gap-3">
                <h1 class="text-3xl font-bold">{{ application.name }}</h1>
                {% if application.status == "running" %}
                <span class="px-3 py-1 rounded-full bg-green-500/10 text-green-400 text-sm border border-green-500/20 flex items-center gap-2">
                    <span class="status-indicator running"></span>
                    Running
                </span>
                {% elif application.status == "stopped" %}
                <span class="px-3 py-1 rounded-full bg-gray-500/10 text-gray-400 text-sm border border-gray-500/20 flex items-center gap-2">
                    <span class="status-indicator stopped"></span>
                    Stopped
                </span>
                {% elif application.status == "error" %}
                <span class="px-3 py-1 rounded-full bg-red-500/10 text-red-400 text-sm border border-red-500/20 flex items-center gap-2">
                    <span class="status-indicator error"></span>
                    Error
                </span>
                {% else %}
                <span class="px-3 py-1 rounded-full bg-yellow-500/10 text-yellow-400 text-sm border border-yellow-500/20 flex items-center gap-2">
                    <span class="status-indicator unknown"></span>
                    {{ application.status }}
                </span>
                {% endif %}
                
            </div>
            <div class="mt-2 flex flex-wrap gap-2 items-center">
                {% if application.app_type == "flask" %}
                <span class="px-3 py-1 rounded-full bg-blue-500/10 text-blue-400 text-sm border border-blue-500/20">Flask (Waitress)</span>
                {% elif application.app_type == "fastapi" %}
                <span class="px-3 py-1 rounded-full bg-green-500/10 text-green-400 text-sm border border-green-500/20">FastAPI (Uvicorn)</span>
                {% elif application.app_type == "django" %}
                <span class="px-3 py-1 rounded-full bg-purple-500/10 text-purple-400 text-sm border border-purple-500/20">Django (Gunicorn)</span>
                {% else %}
                <span class="px-3 py-1 rounded-full bg-gray-500/10 text-gray-400 text-sm border border-gray-500/20">{{ application.app_type }}</span>
                {% endif %}
                <span class="text-gray-400">Port: {{ application.port or 'Not assigned' }}</span>
            </div>
        </div>
        
        <div class="flex items-center gap-3">
            {% if application.status == "running" %}
            <form action="/applications/{{ application.id }}/stop" method="post">
                <button type="submit" class="px-4 py-2 rounded-md bg-yellow-700/20 hover:bg-yellow-700/30 text-yellow-400 border border-yellow-700/30 transition-colors flex items-center gap-2">
                    <i data-lucide="square" class="w-5 h-5"></i>
                    <span>Stop</span>
                </button>
            </form>
            <form action="/applications/{{ application.id }}/restart" method="post">
                <button type="submit" class="px-4 py-2 rounded-md bg-blue-700/20 hover:bg-blue-700/30 text-blue-400 border border-blue-700/30 transition-colors flex items-center gap-2">
                    <i data-lucide="refresh-cw" class="w-5 h-5"></i>
                    <span>Restart</span>
                </button>
            </form>
            {% elif application.status in ["stopped", "error"] %}
            <form action="/applications/{{ application.id }}/start" method="post">
                <button type="submit" class="px-4 py-2 rounded-md bg-green-700/20 hover:bg-green-700/30 text-green-400 border border-green-700/30 transition-colors flex items-center gap-2">
                    <i data-lucide="play" class="w-5 h-5"></i>
                    <span>Start</span>
                </button>
            </form>
            {% endif %}

            <a href="/applications/{{ application.id }}/logs"
                class="px-4 py-2 rounded-md bg-blue-600 hover:bg-blue-700 text-white transition-colors flex items-center gap-2">
                <i data-lucide="monitor" class="w-5 h-5"></i>
                <span>View logs in real time</span>
            </a>

            <button type="button" 
                   onclick="document.getElementById('deleteModal').classList.remove('hidden')"
                   class="px-4 py-2 rounded-md bg-red-700/20 hover:bg-red-700/30 text-red-400 border border-red-700/30 transition-colors flex items-center gap-2">
                <i data-lucide="trash-2" class="w-5 h-5"></i>
                <span>Delete</span>
            </button>
        </div>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
        <!-- Información de la aplicación -->
        <div class="rounded-lg glass-effect overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-800">
                <h2 class="text-xl font-semibold">Information</h2>
            </div>
            <div class="p-6">
                <dl class="grid grid-cols-1 gap-4">
                    <div class="grid grid-cols-3 gap-4 py-2 border-b border-gray-800">
                        <dt class="font-medium text-gray-400">Status:</dt>
                        <dd class="col-span-2 text-white">
                            {% if application.status == "running" %}
                            <span class="px-3 py-1 rounded-full bg-green-500/10 text-green-400 text-sm border border-green-500/20">Running</span>
                            {% elif application.status == "stopped" %}
                            <span class="px-3 py-1 rounded-full bg-gray-500/10 text-gray-400 text-sm border border-gray-500/20">Stopped</span>
                            {% elif application.status == "error" %}
                            <span class="px-3 py-1 rounded-full bg-red-500/10 text-red-400 text-sm border border-red-500/20">Error</span>
                            {% else %}
                            <span class="px-3 py-1 rounded-full bg-yellow-500/10 text-yellow-400 text-sm border border-yellow-500/20">{{ application.status }}</span>
                            {% endif %}
                        </dd>
                    </div>
                    
                    <div class="grid grid-cols-3 gap-4 py-2 border-b border-gray-800">
                        <dt class="font-medium text-gray-400">PID:</dt>
                        <dd class="col-span-2 text-white">{{ application.pid or 'N/A' }}</dd>
                    </div>
                    
                    <div class="grid grid-cols-3 gap-4 py-2 border-b border-gray-800">
                        <dt class="font-medium text-gray-400">Directory:</dt>
                        <dd class="col-span-2">
                            <div class="bg-gray-800 p-2 rounded-md overflow-x-auto font-mono text-sm text-gray-300">
                                {{ application.directory }}
                            </div>
                        </dd>
                    </div>
                    
                    <div class="grid grid-cols-3 gap-4 py-2 border-b border-gray-800">
                        <dt class="font-medium text-gray-400">Main File:</dt>
                        <dd class="col-span-2 text-white font-mono">{{ application.main_file }}</dd>
                    </div>
                    
                    <div class="grid grid-cols-3 gap-4 py-2 border-b border-gray-800">
                        <dt class="font-medium text-gray-400">Created:</dt>
                        <dd class="col-span-2 text-white">{{ application.created_at.strftime('%d/%m/%Y %H:%M:%S') }}</dd>
                    </div>
                    
                    {% if application.status == "running" %}
                    <div class="grid grid-cols-3 gap-4 py-2 border-b border-gray-800">
                        <dt class="font-medium text-gray-400">LAN URL:</dt>
                        <dd class="col-span-2">
                            <a href="http://{{ local_ip }}:{{ application.port }}" target="_blank" class="inline-flex items-center gap-2 px-3 py-1 rounded-md bg-green-900/20 hover:bg-green-900/30 text-green-400 border border-green-800/30 transition-colors">
                                http://{{ local_ip }}:{{ application.port }}
                                <i data-lucide="external-link" class="w-4 h-4"></i>
                            </a>
                        </dd>
                    </div>
                    
                    {% if application.ngrok_url %}
                    <div class="grid grid-cols-3 gap-4 py-2 border-b border-gray-800">
                        <dt class="font-medium text-gray-400">Internet URL (ngrok):</dt>
                        <dd class="col-span-2">
                            <a href="{{ application.ngrok_url }}" target="_blank" class="inline-flex items-center gap-2 px-3 py-1 rounded-md bg-purple-900/20 hover:bg-purple-900/30 text-purple-400 border border-purple-800/30 transition-colors">
                                {{ application.ngrok_url }}
                                <i data-lucide="external-link" class="w-4 h-4"></i>
                            </a>
                        </dd>
                    </div>
                    {% endif %}
                    {% endif %}
                </dl>
            </div>
        </div>
        
        <!-- Información de comandos -->
        <div class="rounded-lg glass-effect overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-800">
                <h2 class="text-xl font-semibold">Commands</h2>
            </div>
            <div class="p-6">
                <div class="mb-6">
                    <h3 class="text-sm font-medium text-gray-400 mb-2">Execution Command:</h3>
                    <div class="bg-gray-800 p-3 rounded-md overflow-x-auto font-mono text-sm text-green-400">
                        {% if application.app_type == "flask" %}
                            python -m waitress --port={{ application.port }} {{ application.main_file.split('.')[0] }}:app
                        {% elif application.app_type == "fastapi" %}
                            uvicorn {{ application.main_file.split('.')[0] }}:app --port={{ application.port }}
                        {% elif application.app_type == "django" %}
                            python -m gunicorn {{ django_project_name }}.wsgi:application --bind=0.0.0.0:{{ application.port }}
                        {% endif %}
                    </div>
                </div>
                
                <div class="mb-6">
                    <h3 class="text-sm font-medium text-gray-400 mb-2">Working Directory:</h3>
                    <div class="bg-gray-800 p-3 rounded-md overflow-x-auto font-mono text-sm text-blue-400">
                        {{ application.directory }}
                    </div>
                </div>
                
                <div>
                    <h3 class="text-sm font-medium text-gray-400 mb-2">Log Files:</h3>
                    <ul class="space-y-2 text-sm">
                        <li class="flex items-center gap-2">
                            <i data-lucide="file-text" class="w-4 h-4 text-gray-400"></i>
                            <span class="font-mono text-gray-300">{{ application.directory }}/logs/stdout.log</span>
                        </li>
                        <li class="flex items-center gap-2">
                            <i data-lucide="file-text" class="w-4 h-4 text-gray-400"></i>
                            <span class="font-mono text-gray-300">{{ application.directory }}/logs/stderr.log</span>
                        </li>
                    </ul>
                </div>

                {% if application.app_type == "django" %}
                <div class="grid grid-cols-3 gap-4 py-2 border-b border-gray-800">
                    <dt class="font-medium text-gray-400">Admin URL:</dt>
                    <dd class="col-span-2">
                        <a href="http://{{ local_ip }}:{{ application.port }}/admin/" target="_blank" class="inline-flex items-center gap-2 px-3 py-1 rounded-md bg-purple-900/20 hover:bg-purple-900/30 text-purple-400 border border-purple-800/30 transition-colors">
                            http://{{ local_ip }}:{{ application.port }}/admin/
                            <i data-lucide="external-link" class="w-4 h-4"></i>
                        </a>
                    </dd>
                </div>
                {% endif %}
            </div>
        </div>
    </div>

    
    {% if application.app_type == "django" %}
    <div class="rounded-lg glass-effect overflow-hidden mb-6"> 
        <div class="px-6 py-4 border-b border-gray-800">
            <h2 class="text-xl font-semibold">Django Migrations</h2>
        </div>
        <div class="p-6">
            <button id="check-migrations" class="px-4 py-2 rounded-md bg-purple-600 hover:bg-purple-700 text-white transition-colors flex items-center gap-2">
                <i data-lucide="database" class="w-4 h-4"></i>
                    <span>Check Migrations</span>
            </button>
        <div id="migrations-result" class="mt-4 hidden"></div>
        </div>
    </div>
    {% endif %}

    <!-- Logs de la aplicación -->
    <div class="rounded-lg glass-effect overflow-hidden mb-6"> 
        <div class="px-6 py-4 border-b border-gray-800 flex justify-between items-center">
            <h2 class="text-xl font-semibold">Event Log</h2>
            <div class="flex gap-2">
                <a href="/api/applications/{{ application.id }}/logs/download?format=csv" class="px-3 py-1 rounded-md border border-gray-700 hover:bg-gray-800 text-gray-300 flex items-center gap-2 transition-colors">
                    <i data-lucide="download" class="w-4 h-4"></i>
                    <span>CSV</span>
                </a>
                <a href="/api/applications/{{ application.id }}/logs/download?format=json" class="px-3 py-1 rounded-md border border-gray-700 hover:bg-gray-800 text-gray-300 flex items-center gap-2 transition-colors">
                    <i data-lucide="download" class="w-4 h-4"></i>
                    <span>JSON</span>
                </a>
            </div>
        </div>
        <div class="overflow-x-auto">
            {% if logs %}
            <table class="w-full">
                <thead class="bg-gray-800/50 text-left">
                    <tr>
                        <th class="px-4 py-3 text-gray-400 font-medium w-48">Date</th>
                        <th class="px-4 py-3 text-gray-400 font-medium w-24">Level</th>
                        <th class="px-4 py-3 text-gray-400 font-medium">Message</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-800">
                    {% for log in logs %}
                    <tr class="hover:bg-white/5 transition-colors">
                        <td class="px-4 py-3 text-sm text-gray-300">{{ log.timestamp.strftime('%d/%m/%Y %H:%M:%S') }}</td>
                        <td class="px-4 py-3">
                            {% if log.level == "info" %}
                            <span class="px-2 py-1 rounded-full bg-blue-500/10 text-blue-400 text-xs border border-blue-500/20">INFO</span>
                            {% elif log.level == "warning" %}
                            <span class="px-2 py-1 rounded-full bg-yellow-500/10 text-yellow-400 text-xs border border-yellow-500/20">WARN</span>
                            {% elif log.level == "error" %}
                            <span class="px-2 py-1 rounded-full bg-red-500/10 text-red-400 text-xs border border-red-500/20">ERROR</span>
                            {% else %}
                            <span class="px-2 py-1 rounded-full bg-gray-500/10 text-gray-400 text-xs border border-gray-500/20">{{ log.level }}</span>
                            {% endif %}
                        </td>
                        <td class="px-4 py-3 text-gray-300">{{ log.message }}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
            {% else %}
            <div class="py-12 text-center">
                <div class="inline-flex p-4 rounded-full bg-gray-800/50 mb-4">
                    <i data-lucide="clipboard-list" class="w-8 h-8 text-gray-400"></i>
                </div>
                <h3 class="text-xl font-semibold mb-2">No events registered</h3>
                <p class="text-gray-400">Events will appear here when you start the application</p>
            </div>
            {% endif %}
        </div>
    </div>
    
    <!-- Logs de salida de la aplicación -->
    <div class="rounded-lg glass-effect overflow-hidden mb-6"> 
        <div class="px-6 py-4 border-b border-gray-800">
            <h2 class="text-xl font-semibold">Application Output Logs</h2>
        </div>
        <div class="p-6">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <!-- stdout.log -->
                <div class="p-4 rounded-lg border border-gray-800 bg-gray-900/30">
                    <div class="flex justify-between items-center mb-3">
                        <h3 class="text-lg font-medium flex items-center gap-2">
                            <i data-lucide="terminal" class="w-5 h-5 text-blue-400"></i>
                            <span>Standard Output (stdout)</span>
                        </h3>
                        <a href="/api/applications/{{ application.id }}/output-logs/download?log_type=stdout" 
                           class="px-3 py-1 rounded-md bg-blue-900/20 hover:bg-blue-900/30 text-blue-400 border border-blue-900/20 flex items-center gap-2 transition-colors">
                            <i data-lucide="download" class="w-4 h-4"></i>
                            <span>Download</span>
                        </a>
                    </div>
                    <p class="text-sm text-gray-400 mb-2">
                        Contains the normal messages and output of the application.
                    </p>
                    <div class="bg-gray-800 p-2 rounded text-xs text-gray-300 font-mono">
                        {{ application.directory }}/logs/stdout.log
                    </div>
                </div>
                
                <!-- stderr.log -->
                <div class="p-4 rounded-lg border border-gray-800 bg-gray-900/30">
                    <div class="flex justify-between items-center mb-3">
                        <h3 class="text-lg font-medium flex items-center gap-2">
                            <i data-lucide="alert-triangle" class="w-5 h-5 text-red-400"></i>
                            <span>Error Output (stderr)</span>
                        </h3>
                        <a href="/api/applications/{{ application.id }}/output-logs/download?log_type=stderr" 
                           class="px-3 py-1 rounded-md bg-red-900/20 hover:bg-red-900/30 text-red-400 border border-red-900/20 flex items-center gap-2 transition-colors">
                            <i data-lucide="download" class="w-4 h-4"></i>
                            <span>Download</span>
                        </a>
                    </div>
                    <p class="text-sm text-gray-400 mb-2">
                        Contains error messages, exceptions, and warnings.
                    </p>
                    <div class="bg-gray-800 p-2 rounded text-xs text-gray-300 font-mono">
                        {{ application.directory }}/logs/stderr.log
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal de confirmación para eliminar -->
<div id="deleteModal" class="fixed inset-0 bg-black/70 backdrop-blur-sm flex justify-center items-center z-50 hidden">
    <div class="bg-gray-900 rounded-lg border border-gray-800 max-w-md w-full p-6 m-4">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-xl font-bold text-white">Confirm Deletion</h3>
            <button type="button" onclick="document.getElementById('deleteModal').classList.add('hidden')" class="text-gray-400 hover:text-white">
                <i data-lucide="x" class="w-5 h-5"></i>
            </button>
        </div>
        <div class="mb-6">
            <p class="mb-2">Are you sure you want to delete the application <strong>{{ application.name }}</strong>?</p>
            <p class="text-red-400 text-sm">This action cannot be undone.</p>
        </div>
        <div class="flex justify-end gap-3">
            <button type="button" onclick="document.getElementById('deleteModal').classList.add('hidden')" class="px-4 py-2 rounded-md border border-gray-700 text-gray-300 hover:bg-gray-800 transition-colors">
                Cancel
            </button>
            <form action="/applications/{{ application.id }}/delete" method="post">
                <button type="submit" class="px-4 py-2 rounded-md bg-red-700/30 hover:bg-red-700/40 text-red-400 border border-red-700/30 transition-colors">
                    Delete Application
                </button>
            </form>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    // Actualizar la página cada 30 segundos si la aplicación está en ejecución
    {% if application.status == "running" %}
    setTimeout(function() {
        location.reload();
    }, 30000);
    {% endif %}
</script>

{% if application.app_type == "django" %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const checkMigrationsBtn = document.getElementById('check-migrations');
        const applyMigrationsBtn = document.getElementById('apply-migrations');
        const resultDiv = document.getElementById('migrations-result');
        
        // Función para verificar migraciones
        function checkMigrations() {
            resultDiv.innerHTML = `
                <div class="p-6 text-center">
                    <i data-lucide="loader-2" class="w-8 h-8 mx-auto mb-3 animate-spin text-purple-400"></i>
                    <p class="text-gray-300">Checking migrations...</p>
                </div>
            `;
            resultDiv.classList.remove('hidden');
            
            // Actualizar íconos
            lucide.createIcons();
            
            fetch('/api/applications/{{ application.id }}/django-migrations')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Error checking migrations');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        // Agrupar migraciones por app
                        const appGroups = {};
                        data.migrations.forEach(m => {
                            if (!appGroups[m.app]) {
                                appGroups[m.app] = [];
                            }
                            appGroups[m.app].push(m);
                        });
                        
                        // Construir HTML
                        let html = `
                            <div class="border border-gray-700 rounded-lg overflow-hidden">
                                <div class="px-4 py-3 bg-gray-800 flex justify-between items-center">
                                    <h3 class="font-medium">Migration Status</h3>
                                    <span class="px-3 py-1 rounded-full ${data.pending_count === 0 ? 'bg-green-500/10 text-green-400 border border-green-500/20' : 'bg-yellow-500/10 text-yellow-400 border border-yellow-500/20'}">
                                        ${data.status}
                                    </span>
                                </div>
                                <div class="divide-y divide-gray-700">
                        `;
                        
                        // Mostrar apps y sus migraciones
                        Object.keys(appGroups).sort().forEach(app => {
                            const migrations = appGroups[app];
                            const pendingCount = migrations.filter(m => !m.applied).length;
                            
                            html += `
                                <div class="p-4">
                                    <div class="flex justify-between items-center mb-2">
                                        <h4 class="font-medium text-gray-300">${app}</h4>
                                        <span class="text-sm ${pendingCount === 0 ? 'text-green-400' : 'text-yellow-400'}">
                                            ${pendingCount === 0 ? '✓ Al día' : `${pendingCount} pendiente${pendingCount !== 1 ? 's' : ''}`}
                                        </span>
                                    </div>
                                    <ul class="space-y-1 pl-2">
                            `;
                            
                            migrations.forEach(m => {
                                html += `
                                    <li class="flex items-center gap-2 text-sm">
                                        <span class="${m.applied ? 'text-green-400' : 'text-gray-500'}">
                                            ${m.applied ? '✓' : '○'}
                                        </span>
                                        <span class="${m.applied ? 'text-gray-300' : 'text-gray-500'}">${m.name}</span>
                                    </li>
                                `;
                            });
                            
                            html += `
                                    </ul>
                                </div>
                            `;
                        });
                        
                        html += `
                                </div>
                            </div>
                        `;
                        
                        resultDiv.innerHTML = html;
                    } else {
                        // Mostrar error
                        resultDiv.innerHTML = `
                            <div class="p-4 rounded-md bg-red-500/10 border border-red-500/30 text-red-400">
                                <div class="flex items-start gap-3">
                                    <i data-lucide="alert-triangle" class="w-5 h-5 mt-0.5"></i>
                                    <div>
                                        <h3 class="font-medium mb-1">Error al verificar migraciones</h3>
                                        <p class="text-sm">${data.error}</p>
                                    </div>
                                </div>
                            </div>
                        `;
                    }
                    
                    // Actualizar íconos
                    lucide.createIcons();
                })
                .catch(error => {
                    resultDiv.innerHTML = `
                        <div class="p-4 rounded-md bg-red-500/10 border border-red-500/30 text-red-400">
                            <div class="flex items-start gap-3">
                                <i data-lucide="alert-triangle" class="w-5 h-5 mt-0.5"></i>
                                <div>
                                    <h3 class="font-medium mb-1">Error</h3>
                                    <p class="text-sm">${error.message}</p>
                                </div>
                            </div>
                        </div>
                    `;
                    lucide.createIcons();
                });
        }
        
        // Configurar botones
        if (checkMigrationsBtn) {
            checkMigrationsBtn.addEventListener('click', checkMigrations);
        }
        
        // TODO: Implementar la función para aplicar migraciones
        if (applyMigrationsBtn) {
            applyMigrationsBtn.addEventListener('click', function() {
                // Esta funcionalidad requeriría otra API que ejecute "python manage.py migrate"
                alert('Funcionalidad no implementada. Necesitarías crear un endpoint adicional para ejecutar "python manage.py migrate"');
            });
        }
    });
</script>
{% endif %}

{% endblock %}