{% extends "base.html" %}

{% block title %}Editar {{ application.name }} - Administración{% endblock %}
{% block header_title %}Editar Aplicación{% endblock %}

{% block content %}
<div class="page-header">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ url_for('admin_dashboard') }}">Administración</a></li>
                    <li class="breadcrumb-item"><a href="{{ url_for('admin_applications') }}">Aplicaciones</a></li>
                    <li class="breadcrumb-item active">Editar</li>
                </ol>
            </nav>
            <h1 class="page-title">Editar {{ application.name }}</h1>
            <p class="page-subtitle">Actualiza la información y configuración de la aplicación</p>
        </div>
        <div class="d-flex gap-2">
            {% if application.is_private %}
            <a href="{{ url_for('admin_application_permissions', app_id=application.id) }}" class="btn btn-warning">
                <i class="fas fa-lock me-2"></i>Gestionar Permisos
            </a>
            {% endif %}
            <a href="{{ url_for('admin_applications') }}" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left me-2"></i>Volver
            </a>
        </div>
    </div>
</div>

<div class="row justify-content-center">
    <div class="col-lg-10">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-edit me-2"></i>Información de la Aplicación
                </h5>
            </div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data" id="editAppForm" novalidate>
                    <div class="row">
                        <!-- Información Básica -->
                        <div class="col-md-6">
                            <h6 class="text-muted mb-3">Información Básica</h6>

                            <div class="mb-3">
                                <label for="name" class="form-label">
                                    <i class="fas fa-tag me-1 text-primary"></i>
                                    Nombre de la Aplicación <span class="text-danger">*</span>
                                </label>
                                <input type="text"
                                       class="form-control"
                                       id="name"
                                       name="name"
                                       value="{{ application.name }}"
                                       required>
                                <div class="invalid-feedback">
                                    Por favor ingresa el nombre de la aplicación.
                                </div>
                            </div>

                            <div class="mb-3">
                                <label for="description" class="form-label">
                                    <i class="fas fa-align-left me-1 text-primary"></i>
                                    Descripción
                                </label>
                                <textarea class="form-control"
                                          id="description"
                                          name="description"
                                          rows="3">{{ application.description or '' }}</textarea>
                            </div>

                            <div class="mb-3">
                                <label for="category_id" class="form-label">
                                    <i class="fas fa-folder me-1 text-primary"></i>
                                    Categoría
                                </label>
                                <select class="form-control" id="category_id" name="category_id">
                                    <option value="">Seleccionar categoría</option>
                                    {% for category in categories %}
                                    <option value="{{ category.id }}"
                                            {% if application.category_id == category.id %}selected{% endif %}>
                                        {{ category.name }}
                                    </option>
                                    {% endfor %}
                                </select>
                            </div>

                            <div class="mb-3">
                                <label for="tags" class="form-label">
                                    <i class="fas fa-tags me-1 text-primary"></i>
                                    Etiquetas
                                </label>
                                <input type="text"
                                       class="form-control"
                                       id="tags"
                                       name="tags"
                                       value="{{ application.tags or '' }}"
                                       placeholder="servidor, producción, desarrollo">
                            </div>

                            <div class="mb-3">
                                <label for="icon" class="form-label">
                                    <i class="fas fa-image me-1 text-primary"></i>
                                    Icono de la Aplicación
                                </label>
                                {% if application.icon_filename %}
                                <div class="mb-2">
                                    <img src="{{ application.icon_url }}" alt="Icono actual"
                                         style="width: 48px; height: 48px; border-radius: 8px;">
                                    <small class="text-muted ms-2">Icono actual</small>
                                </div>
                                {% endif %}
                                <input type="file"
                                       class="form-control"
                                       id="icon"
                                       name="icon"
                                       accept="image/*">
                                <div class="form-text">Deja vacío para mantener el icono actual</div>
                            </div>
                        </div>

                        <!-- Configuración de Red -->
                        <div class="col-md-6">
                            <h6 class="text-muted mb-3">Configuración de Acceso</h6>

                            <div class="mb-3">
                                <label for="ip_address" class="form-label">
                                    <i class="fas fa-globe me-1 text-primary"></i>
                                    Dirección IP <span class="text-danger">*</span>
                                </label>
                                <input type="text"
                                       class="form-control"
                                       id="ip_address"
                                       name="ip_address"
                                       value="{{ application.ip_address }}"
                                       required>
                                <div class="invalid-feedback">
                                    Por favor ingresa una dirección IP válida.
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="protocol" class="form-label">
                                            <i class="fas fa-shield-alt me-1 text-primary"></i>
                                            Protocolo
                                        </label>
                                        <select class="form-control" id="protocol" name="protocol">
                                            <option value="http" {% if application.protocol == 'http' %}selected{% endif %}>HTTP</option>
                                            <option value="https" {% if application.protocol == 'https' %}selected{% endif %}>HTTPS</option>
                                            <option value="ftp" {% if application.protocol == 'ftp' %}selected{% endif %}>FTP</option>
                                            <option value="ssh" {% if application.protocol == 'ssh' %}selected{% endif %}>SSH</option>
                                            <option value="rdp" {% if application.protocol == 'rdp' %}selected{% endif %}>RDP</option>
                                            <option value="telnet" {% if application.protocol == 'telnet' %}selected{% endif %}>Telnet</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="port" class="form-label">
                                            <i class="fas fa-plug me-1 text-primary"></i>
                                            Puerto
                                        </label>
                                        <input type="number"
                                               class="form-control"
                                               id="port"
                                               name="port"
                                               value="{{ application.port or '' }}"
                                               min="1"
                                               max="65535">
                                    </div>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label for="url_path" class="form-label">
                                    <i class="fas fa-route me-1 text-primary"></i>
                                    Ruta Adicional
                                </label>
                                <input type="text"
                                       class="form-control"
                                       id="url_path"
                                       name="url_path"
                                       value="{{ application.url_path }}">
                            </div>

                            <!-- Vista previa de URL -->
                            <div class="mb-3">
                                <label class="form-label">
                                    <i class="fas fa-link me-1 text-success"></i>
                                    URL Final
                                </label>
                                <div class="p-2 bg-light rounded border">
                                    <code id="urlPreview">{{ application.full_url }}</code>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Configuración de Autenticación -->
                    <hr class="my-4">
                    <h6 class="text-muted mb-3">Configuración de Autenticación</h6>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="card border-light">
                                <div class="card-body">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" id="requires_auth" name="requires_auth"
                                               {% if application.requires_auth %}checked{% endif %}>
                                        <label class="form-check-label" for="requires_auth">
                                            <strong>Requiere Autenticación Adicional</strong>
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6" id="authConfig" style="display: {{ 'block' if application.requires_auth else 'none' }};">
                            <div class="mb-3">
                                <label for="auth_username" class="form-label">
                                    <i class="fas fa-user me-1 text-primary"></i>
                                    Usuario por Defecto
                                </label>
                                <input type="text"
                                       class="form-control"
                                       id="auth_username"
                                       name="auth_username"
                                       value="{{ application.auth_username or '' }}">
                            </div>
                        </div>
                    </div>

                    <!-- CONFIGURACIÓN DE PRIVACIDAD -->
                    <hr class="my-4">
                    <h6 class="text-muted mb-3">Configuración de Privacidad</h6>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="is_private" name="is_private"
                                       {% if application.is_private %}checked{% endif %}>
                                <label class="form-check-label" for="is_private">
                                    <strong>Aplicación Privada</strong>
                                </label>
                            </div>
                            <div class="form-text mt-2">
                                Marca si la aplicación debe ser accesible solo para usuarios autorizados.
                            </div>
                        </div>

                        <div class="col-md-6" id="departmentsContainer" style="display: {{ 'block' if application.is_private else 'none' }};">
                            <div class="mb-3">
                                <label for="allowed_departments" class="form-label">
                                    <i class="fas fa-users me-1 text-primary"></i>
                                    Departamentos Permitidos
                                </label>
                                <input type="text"
                                       class="form-control"
                                       id="allowed_departments"
                                       name="allowed_departments"
                                       value="{{ application.allowed_departments or '' }}"
                                       placeholder="IT, Contabilidad, Gerencia">
                                <div class="form-text">
                                    Departamentos separados por comas.
                                </div>
                            </div>

                            {% if departments %}
                            <div class="mt-2">
                                <small class="text-muted">Departamentos disponibles:</small>
                                <div class="d-flex flex-wrap gap-1 mt-1">
                                    {% for dept in departments %}
                                    <span class="badge bg-light text-dark cursor-pointer" onclick="addDepartment('{{ dept }}')">{{ dept }}</span>
                                    {% endfor %}
                                </div>
                            </div>
                            {% endif %}
                        </div>
                    </div>

                    <div class="alert alert-warning alert-sm" id="privacyInfo" style="display: {{ 'block' if application.is_private else 'none' }};">
                        <small>
                            <i class="fas fa-exclamation-triangle me-1"></i>
                            <strong>Aplicación Privada:</strong> Solo será visible para administradores, usuarios de departamentos permitidos, y usuarios con permisos específicos.
                            {% if application.is_private %}
                            <br><a href="{{ url_for('admin_application_permissions', app_id=application.id) }}" class="alert-link">
                                Gestionar permisos específicos
                            </a>
                            {% endif %}
                        </small>
                    </div>

                    <!-- Estadísticas de la aplicación -->
                    <hr class="my-4">
                    <h6 class="text-muted mb-3">Estadísticas</h6>

                    <div class="row">
                        <div class="col-md-3">
                            <div class="text-center">
                                <h4 class="text-primary mb-1">{{ application.access_count }}</h4>
                                <small class="text-muted">Total Accesos</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h4 class="text-info mb-1">{{ application.favorites.count() }}</h4>
                                <small class="text-muted">En Favoritos</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h4 class="text-warning mb-1">{{ application.permissions.count() }}</h4>
                                <small class="text-muted">Permisos Específicos</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h4 class="text-success mb-1">{{ application.created_at.strftime('%d/%m/%Y') }}</h4>
                                <small class="text-muted">Fecha Creación</small>
                            </div>
                        </div>
                    </div>

                    <!-- Botones de acción -->
                    <div class="d-flex justify-content-between align-items-center mt-4 pt-3 border-top">
                        <div class="d-flex gap-2">
                            <a href="{{ application.full_url }}" target="_blank" class="btn btn-outline-success">
                                <i class="fas fa-external-link-alt me-1"></i>Probar Aplicación
                            </a>
                            {% if application.is_private %}
                            <a href="{{ url_for('admin_application_permissions', app_id=application.id) }}" class="btn btn-outline-warning">
                                <i class="fas fa-lock me-1"></i>Gestionar Permisos
                            </a>
                            {% endif %}
                        </div>

                        <div class="d-flex gap-2">
                            <a href="{{ url_for('admin_applications') }}" class="btn btn-outline-secondary">
                                <i class="fas fa-times me-2"></i>Cancelar
                            </a>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save me-2"></i>Guardar Cambios
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('editAppForm');
    const requiresAuthCheckbox = document.getElementById('requires_auth');
    const authConfig = document.getElementById('authConfig');
    const isPrivateCheckbox = document.getElementById('is_private');
    const departmentsContainer = document.getElementById('departmentsContainer');
    const privacyInfo = document.getElementById('privacyInfo');

    // Toggle configuración de autenticación
    requiresAuthCheckbox.addEventListener('change', function() {
        authConfig.style.display = this.checked ? 'block' : 'none';
    });

    // Toggle configuración de privacidad
    isPrivateCheckbox.addEventListener('change', function() {
        departmentsContainer.style.display = this.checked ? 'block' : 'none';
        privacyInfo.style.display = this.checked ? 'block' : 'none';
    });

    // Actualizar vista previa de URL
    function updateUrlPreview() {
        const protocol = document.getElementById('protocol').value;
        const ip = document.getElementById('ip_address').value;
        const port = document.getElementById('port').value;
        const path = document.getElementById('url_path').value;

        let url = protocol + '://' + ip;

        if (port && !['80', '443'].includes(port)) {
            url += ':' + port;
        }

        url += (path || '/');

        document.getElementById('urlPreview').textContent = url;
    }

    // Event listeners para actualizar URL
    ['protocol', 'ip_address', 'port', 'url_path'].forEach(id => {
        document.getElementById(id).addEventListener('input', updateUrlPreview);
    });

    // Validación del formulario
    form.addEventListener('submit', function(e) {
        e.preventDefault();

        if (validateForm()) {
            this.submit();
        }
    });

    function validateForm() {
        let isValid = true;

        // Limpiar validaciones anteriores
        form.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
        form.querySelectorAll('.is-valid').forEach(el => el.classList.remove('is-valid'));

        // Validar campos requeridos
        const name = document.getElementById('name');
        const ipAddress = document.getElementById('ip_address');

        if (!name.value.trim()) {
            name.classList.add('is-invalid');
            isValid = false;
        } else {
            name.classList.add('is-valid');
        }

        if (!ipAddress.value.trim()) {
            ipAddress.classList.add('is-invalid');
            isValid = false;
        } else {
            // Validación básica de IP/hostname
            const ipPattern = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
            if (ipPattern.test(ipAddress.value.trim())) {
                ipAddress.classList.add('is-valid');
            } else {
                ipAddress.classList.add('is-invalid');
                isValid = false;
            }
        }

        return isValid;
    }

    // Inicializar vista previa
    updateUrlPreview();
});

// Función para agregar departamento desde las sugerencias
function addDepartment(dept) {
    const input = document.getElementById('allowed_departments');
    const currentValue = input.value.trim();

    if (!currentValue) {
        input.value = dept;
    } else if (!currentValue.split(',').map(d => d.trim()).includes(dept)) {
        input.value = currentValue + ', ' + dept;
    }

    input.focus();
}
</script>
{% endblock %}
