{% extends "base.html" %}

{% block title %}{{ project.descripcion }} - ARCH{% endblock %}

{% block styles %}
<link rel="stylesheet" href="{{ url_for('static', filename='css/projects.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/documents.css') }}">
{% endblock %}

{% block page_title %}Proyecto: {{ project.descripcion }}{% endblock %}

{% block content %}
<div class="row mb-4">
    <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">Detalles del Proyecto</h5>
                <span class="badge bg-{{ 'success' if project.estado == 'activo' else 'danger' }}">
                    {{ project.estado|capitalize }}
                </span>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <dl class="row">
                            <dt class="col-sm-4">Código:</dt>
                            <dd class="col-sm-8">{{ project.codigo }}</dd>
                            
                            <dt class="col-sm-4">Cliente:</dt>
                            <dd class="col-sm-8">{{ project.cliente }}</dd>
                            
                            <dt class="col-sm-4">Destinación:</dt>
                            <dd class="col-sm-8">{{ project.destinacion or 'No especificada' }}</dd>
                        </dl>
                    </div>
                    <div class="col-md-6">
                        <dl class="row">
                            <dt class="col-sm-4">Año:</dt>
                            <dd class="col-sm-8">{{ project.ano_creacion }}</dd>
                            
                            <dt class="col-sm-4">Creación:</dt>
                            <dd class="col-sm-8">{{ project.fecha_creacion|replace('T', ' ')|replace('Z', '') }}</dd>
                            
                            <dt class="col-sm-4">Creado por:</dt>
                            <dd class="col-sm-8">{{ project.creado_por }}</dd>
                        </dl>
                    </div>
                </div>
                
                <hr>
                
                <div class="row">
                    <div class="col-md-6">
                        <dl class="row">
                            <dt class="col-sm-4">Proyecto padre:</dt>
                            <dd class="col-sm-8">
                                {% if project.proyecto_padre %}
                                <a href="{{ url_for('projects.view', project_id=project.proyecto_padre|replace('PROJ', '')|int) }}">
                                    {{ project.proyecto_padre }}
                                </a>
                                {% else %}
                                <em>Ninguno</em>
                                {% endif %}
                            </dd>
                            
                            <dt class="col-sm-4">Esquema:</dt>
                            <dd class="col-sm-8">{{ project.esquema }}</dd>
                        </dl>
                    </div>
                    <div class="col-md-6">
                        <dl class="row">
                            <dt class="col-sm-4">Última modificación:</dt>
                            <dd class="col-sm-8">{{ project.ultima_modificacion|replace('T', ' ')|replace('Z', '') }}</dd>
                            
                            <dt class="col-sm-4">Modificado por:</dt>
                            <dd class="col-sm-8">{{ project.modificado_por }}</dd>
                        </dl>
                    </div>
                </div>
            </div>
            <div class="card-footer d-flex justify-content-between">
                <a href="{{ url_for('projects.list') }}" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-left"></i> Volver a la lista
                </a>
                
                <div class="btn-group">
                    {% if current_user.has_permission(5000) and project.estado == 'activo' %}
                    <a href="{{ url_for('projects.edit', project_id=project.codigo|replace('PROJ', '')|int) }}" 
                       class="btn btn-warning">
                        <i class="bi bi-pencil"></i> Editar Proyecto
                    </a>
                    {% endif %}
                    
                    {% if current_user.has_permission(1000) and project.estado == 'activo' %}
                    <a href="{{ url_for('projects.create') }}?padre={{ project.codigo }}" 
                       class="btn btn-info">
                        <i class="bi bi-diagram-3"></i> Crear Subproyecto
                    </a>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">Información</h5>
            </div>
            <div class="card-body">
                <p>
                    <strong>Documentos:</strong>
                    <span class="badge bg-info">{{ document_count }}</span>
                </p>
                
                <p>
                    <strong>Subproyectos:</strong>
                    <span class="badge bg-info">{{ children|length }}</span>
                </p>
                
                {% if project.estado == 'activo' and current_user.has_permission(1000) %}
                <hr>
                
                <div class="d-grid gap-2">
                    <a href="{{ url_for('documents.upload', project_id=project.codigo|replace('PROJ', '')|int) }}" 
                       class="btn btn-success">
                        <i class="bi bi-upload"></i> Subir Documento
                    </a>
                    
                    <a href="{{ url_for('documents.export', project_id=project.codigo|replace('PROJ', '')|int) }}" 
                       class="btn btn-primary">
                        <i class="bi bi-box-arrow-down"></i> Exportar Proyecto
                    </a>
                </div>
                {% endif %}
            </div>
        </div>
        
        {% if children %}
        <div class="card mt-3">
            <div class="card-header">
                <h5 class="card-title mb-0">Subproyectos</h5>
            </div>
            <div class="card-body p-0">
                <div class="list-group list-group-flush">
                    {% for child in children %}
                    <a href="{{ url_for('projects.view', project_id=child.codigo|replace('PROJ', '')|int) }}" 
                       class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                        {{ child.descripcion }}
                        <span class="badge bg-{{ 'success' if child.estado == 'activo' else 'danger' }} rounded-pill">
                            {{ child.estado|capitalize }}
                        </span>
                    </a>
                    {% endfor %}
                </div>
            </div>
        </div>
        {% endif %}
    </div>
</div>

<!-- Sección de documentos -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">Documentos del Proyecto</h5>
                <a href="{{ url_for('documents.list', project_id=project.codigo|replace('PROJ', '')|int) }}" 
                   class="btn btn-sm btn-outline-primary">
                    Ver todos
                </a>
            </div>
            <div class="card-body">
                <div id="documents-container">
                    <div class="text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Cargando...</span>
                        </div>
                        <p class="mt-2">Cargando documentos...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script src="{{ url_for('static', filename='js/projects.js') }}"></script>
<script>
    // Cargar documentos del proyecto mediante AJAX
    $(document).ready(function() {
        $.ajax({
            url: "{{ url_for('documents.api_list', project_id=project.codigo|replace('PROJ', '')|int) }}",
            type: "GET",
            dataType: "json",
            success: function(data) {
                displayDocuments(data);
            },
            error: function() {
                $("#documents-container").html(
                    '<div class="alert alert-danger">Error al cargar los documentos.</div>'
                );
            }
        });
    });
    
    function displayDocuments(documents) {
        if (documents.length === 0) {
            $("#documents-container").html(
                '<div class="alert alert-info">No hay documentos en este proyecto.</div>'
            );
            return;
        }
        
        let html = '<div class="table-responsive">' +
                   '<table class="table table-hover table-striped">' +
                   '<thead class="table-light">' +
                   '<tr>' +
                   '<th>Nombre</th>' +
                   '<th>Tipo</th>' +
                   '<th>Última versión</th>' +
                   '<th>Creado por</th>' +
                   '<th>Acciones</th>' +
                   '</tr>' +
                   '</thead>' +
                   '<tbody>';
        
        documents.forEach(function(doc) {
            // Obtener la última versión
            let latestVersion = doc.versions.reduce((prev, current) => 
                (prev.version > current.version) ? prev : current
            );
            
            // Determinar ícono según tipo MIME
            let icon = '<i class="bi bi-file-earmark"></i>';
            if (latestVersion.mime_type.includes('pdf')) {
                icon = '<i class="bi bi-file-earmark-pdf"></i>';
            } else if (latestVersion.mime_type.includes('image')) {
                icon = '<i class="bi bi-file-earmark-image"></i>';
            } else if (latestVersion.mime_type.includes('zip')) {
                icon = '<i class="bi bi-file-earmark-zip"></i>';
            } else if (latestVersion.mime_type.includes('text')) {
                icon = '<i class="bi bi-file-earmark-text"></i>';
            }
            
            html += '<tr>' +
                    '<td>' + icon + ' ' + doc.original_filename + '</td>' +
                    '<td>' + latestVersion.mime_type + '</td>' +
                    '<td>v' + latestVersion.version + ' (' + latestVersion.created_at.replace('T', ' ').replace('Z', '') + ')</td>' +
                    '<td>' + latestVersion.created_by + '</td>' +
                    '<td>' +
                    '<div class="btn-group btn-group-sm">' +
                    '<a href="/documents/' + {{ project.codigo|replace('PROJ', '')|int }} + '/' + doc.id + '" class="btn btn-primary" title="Ver versiones">' +
                    '<i class="bi bi-eye"></i>' +
                    '</a>' +
                    '<a href="/documents/' + {{ project.codigo|replace('PROJ', '')|int }} + '/' + doc.id + '/download/' + latestVersion.version + '" class="btn btn-success" title="Descargar última versión">' +
                    '<i class="bi bi-download"></i>' +
                    '</a>' +
                    '</div>' +
                    '</td>' +
                    '</tr>';
        });
        
        html += '</tbody></table></div>';
        
        $("#documents-container").html(html);
    }
</script>
{% endblock %}