// Imports de los documentos
import { addDocument } from "../../hooks/documents/publishDocument.js";
import { deleteDocument } from "../../hooks/documents/deleteDocument.js";
import { downloadDocument } from "../../hooks/documents/downloadDocument.js";
//Import para las URLs protegidas
import { modalCreateProtectedUrl } from "./components/modals/ModalCreateProtectedUrl.js";
import { createProtectedUrl } from "../../hooks/urls/createProtectedUrl.js";
import { getProtectedUrl } from "../../hooks/urls/getProtectedUrl.js";
// Import del modal de subida de evidencias
import { modalUploadEvidence } from "./components/modals/ModalUploadEvidence.js";

import Stage from "../../modules/Stage.js";
import Member from "../../modules/Member.js";

// Project id - variable global del fichero util
const projectId = window.location.pathname.split("/")[2]; // Obtiene la ruta
const stageInstance = new Stage(projectId); // Instancia la clase Stage
const memberInstance = new Member(projectId); // Instancia la clase Member

// Muestra la lista de miembros del proyecto
if (document?.getElementById("modal_ListMembers")) {
    console.log("Cargando lista de miembros...");
    document.getElementById('modal_ListMembers').addEventListener('click', async () => {
        memberInstance.showListMembers();
    });
}

// Lógica para abrir el modal de agregar una etapa
document.addEventListener("click", (e) => {
    // para abrir el modal de agregar una etapa 
    const addStageBtn = e.target.closest(".add-stage-btn, .add-root-stage-btn");
    if (!addStageBtn) return;

    const parentId = addStageBtn.dataset.parentId || null;
    stageInstance.add(parentId);
});

// Lógica para mostrar los detalles de una etapa y poder actualizarla
document.addEventListener('click', async (e) => {
    const stageHeader = e.target.closest(".stage-header");

    if (!stageHeader) return;

    const stageId = stageHeader.getAttribute("data-stage-id");
    if (!stageId) return;

    stageInstance.showDetails(stageId);
});

// Lógica para eliminar una etapa
document.addEventListener('click', async (e) => {
    const stageHeader = e.target.closest("#btn_deleteStage");

    if (!stageHeader) return;

    const stageId = stageHeader.getAttribute("data-stage-id");
    if (!stageId) return;

    stageInstance.remove(stageId);
});

// Lógica para el árbol de etapas y la interacción
document.addEventListener("DOMContentLoaded", () => {
    const tree = document.getElementById("stage-tree");

    tree.addEventListener("click", function(e) {
        const toggle = e.target.closest(".stage-toggle");

        if (toggle) {
            e.stopPropagation();
            const stageItem = toggle.closest(".stage-item");
            const children = stageItem.querySelector(".stage-children");

            if (children) {
                children.classList.toggle("hidden");
                toggle.classList.toggle("open");
            }
            return;
        }
    });
});

// Abrir modal de subida de documento
document.addEventListener("click", (e) => {
    const uploadBtn = e.target.closest("#btnOpenUploadModal");
    if (!uploadBtn) return;

    const stageId = uploadBtn.dataset.stageId;
    const stageName = uploadBtn.dataset.stageName;

    if (!stageId || !stageName) {
        console.error("No se encontró stageId o stageName");
        return;
    }

    modalUploadEvidence.open({ id: stageId, name: stageName });
});

// Función para agregar un documento al DOM dinámicamente
async function addDocumentToDOM(documentData, stageId) {
    const { extensionIcons } = await import("../../utils/icons.js");
    const { formatDate } = await import("../../utils/formatter.js");
    
    const extension = documentData?.file_name?.split('.').pop()?.toLowerCase() || 'desconocido';
    const iconSVG = extensionIcons[extension] || extensionIcons['unknown'];
    
    const documentHTML = `
        <div class="border border-zinc-200 rounded-lg shadow-sm hover:shadow-lg transition-all duration-200 w-full flex flex-col sm:flex-row justify-between items-start p-4 gap-4 bg-white">
            <div class="flex items-center gap-3 flex-shrink-0">
                ${iconSVG}
            </div>
            <div class="flex flex-col flex-grow gap-1 overflow-hidden">
                <h3 class="font-semibold text-zinc-800 truncate">${documentData?.name_document || documentData?.file_name}</h3>
                <span class="text-xs text-zinc-500">${formatDate(documentData?.created_at)}</span>
                <p class="text-xs text-zinc-500 truncate">Subido por: <span class="text-blue-500">@${documentData.user?.username || "Desconocido"}</span></p>
                <p class="text-xs text-zinc-400 truncate">${documentData?.description_document || "Sin descripción"}</p>
            </div>
            <div class="flex gap-2 items-center flex-shrink-0 mt-2 sm:mt-0">
                <button class="w-full justify-between flex items-center gap-1 bg-blue-100 text-blue-600 hover:bg-blue-200 px-3 py-1 rounded-md text-sm transition-all duration-200" data-doc-id="${documentData?.id}" data-action="download">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-5">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M9 8.25H7.5a2.25 2.25 0 0 0-2.25 2.25v9a2.25 2.25 0 0 0 2.25 2.25h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25H15M9 12l3 3m0 0 3-3m-3 3V2.25"/>
                    </svg>
                </button>
                <button class="w-full justify-between flex items-center gap-1 bg-zinc-100 text-zinc-300 hover:bg-zinc-200 px-3 py-1 rounded-md text-sm transition-all duration-200" data-doc-id="${documentData?.id}" data-action="edit">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-5">
                        <path stroke-linecap="round" stroke-linejoin="round" d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10" />
                    </svg>
                </button>
                <button class="w-full justify-between flex items-center gap-1 bg-red-100 text-red-600 hover:bg-red-200 px-3 py-1 rounded-md text-sm transition-all duration-200" data-doc-id="${documentData?.id}" data-action="delete">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-5">
                        <path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"/>
                    </svg>
                </button>
            </div>
        </div>
    `;
    
    // Buscar el contenedor específico de documentos
    const containerDocuments = document.getElementById('containerDocuments');
    if (!containerDocuments) {
        console.warn('No se encontró el contenedor containerDocuments');
        return;
    }

    // Buscar si hay mensaje de "No hay documentos"
    const emptyMessage = containerDocuments.querySelector('.text-center.py-8');
    
    if (emptyMessage) {
        // Reemplazar el mensaje vacío con el nuevo documento
        emptyMessage.outerHTML = documentHTML;
    } else {
        // Insertar al final del contenedor de documentos
        containerDocuments.insertAdjacentHTML('beforeend', documentHTML);
    }
}

// Manejar el envío del formulario del modal
document.addEventListener("submit", async (e) => {
    if (e.target.id !== "formUploadEvidence") return;
    
    e.preventDefault();

    const formData = new FormData(e.target);
    const submitBtn = document.getElementById("submitUpload");
    
    // Validar que hay un archivo
    if (!formData.get('document') || formData.get('document').size === 0) {
        alert('Por favor selecciona un archivo');
        return;
    }

    // Deshabilitar botón y mostrar loading
    submitBtn.disabled = true;
    submitBtn.innerHTML = `
        <svg class="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        Subiendo...
    `;

    try {
        const stageId = formData.get('stage_id');
        const file = formData.get('document');
        const name = formData.get('name_document');
        const description = formData.get('description_document');

        const response = await addDocument(stageId, file, name, description);

        if (response?.success && response?.data) {
            // Agregar el documento al DOM dinámicamente
            await addDocumentToDOM(response.data, stageId);
            
            // Cerrar modal después de agregar al DOM
            modalUploadEvidence.close();
        } else {
            alert('Hubo un problema al subir el documento. Por favor intenta de nuevo.');
        }
    } catch (error) {
        console.error('Error al subir documento:', error);
        alert('Error al subir el documento. Por favor intenta de nuevo.');
    } finally {
        // Restaurar botón siempre
        submitBtn.disabled = false;
        submitBtn.innerHTML = `
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5">
                <path fill-rule="evenodd" d="M10.5 3.75a6 6 0 0 0-5.98 6.496A5.25 5.25 0 0 0 6.75 20.25H18a4.5 4.5 0 0 0 2.206-8.423 3.75 3.75 0 0 0-4.133-4.303A6.001 6.001 0 0 0 10.5 3.75Zm2.03 5.47a.75.75 0 0 0-1.06 0l-3 3a.75.75 0 1 0 1.06 1.06l1.72-1.72v4.94a.75.75 0 0 0 1.5 0v-4.94l1.72 1.72a.75.75 0 1 0 1.06-1.06l-3-3Z" clip-rule="evenodd" />
            </svg>
            Subir documento
        `;
    }
});

// listener para descargar un documento de una etapa
document.addEventListener("click", (e) => {
    const btn = e.target.closest("[data-action='download']");
    if (!btn) return;

    const documentId = btn.dataset.docId;
    downloadDocument(documentId);
});

// listener para eliminar un documento de una etapa
document.addEventListener("click", async (e) => {
    const btn = e.target.closest("[data-action='delete']");
    
    if (!btn) return;

    if(!confirm("Al eliminar este documento, se perderá de forma permanente. ¿Seguro que quieres continuar?")) return;
    
    const documentId = btn.dataset.docId;
    const response = await deleteDocument(documentId);

    if(!response) return;
    
    // Eliminar el documento del DOM dinámicamente
    const documentCard = btn.closest('.border.border-zinc-200.rounded-lg');
    if (documentCard) {
        const containerDocuments = document.getElementById('containerDocuments');
        
        // Contar cuántos documentos quedan antes de eliminar
        const remainingDocs = containerDocuments?.querySelectorAll('.border.border-zinc-200.rounded-lg');
        
        // Eliminar el documento
        documentCard.remove();
        
        // Si era el último documento, mostrar mensaje vacío
        if (remainingDocs && remainingDocs.length === 1) {
            containerDocuments.innerHTML = '<div class="text-center py-8 text-zinc-500 text-sm border border-dashed border-zinc-300 rounded-lg bg-zinc-50">No hay documentos cargados en esta etapa</div>';
        }
    }
});

// Actualiza el semáforo de una etapa
document.addEventListener('click', async (e) => {
    const btn = e.target.closest("#btn_updateTrafficLight");
    if (!btn) return;
    const stageId = btn.getAttribute("data-stage-id");
    if (!stageId) return;
    stageInstance.updateLightTraffic(stageId, btn.dataset.trafficLight);
});

    // crea el enlace protegido
if(document?.getElementById("modal_createProtectedUrl")){
    document.getElementById('modal_createProtectedUrl').addEventListener('click', async () => {
    const protectedUrl = await getProtectedUrl(projectId);
    modalCreateProtectedUrl.open({ url: protectedUrl?.data || "" });
    setTimeout(() => {
        const generateBtn = document.getElementById('generateProtectedUrlBtn');
        const copyBtn = document.getElementById('copyProtectedUrlBtn');
        const urlInput = document.getElementById('protectedUrlInput');
        generateBtn.addEventListener('click', async () => {
            const response = await createProtectedUrl(projectId);
            if (!response) return;
            urlInput.value = response.url;
        });
        copyBtn.addEventListener('click', () => {
            navigator.clipboard.writeText(urlInput.value)
            .then(() => {
                alert("Texto copiado: " + urlInput.value);
            })
            .catch(err => {
                console.error("Error al copiar: ", err);
            });
        });
    }, 50);
});
}

// Maneja la descarga del proyecto completo
document.addEventListener('click', (e) => {
    const downloadBtn = e.target.closest('#downloadProjectBtn');
    if (!downloadBtn) return;
    
    // Cambiar el estado del botón
    const originalContent = downloadBtn.innerHTML;
    downloadBtn.innerHTML = `
        <svg class="animate-spin size-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        <span class="text-sm">Preparando descarga...</span>
    `;
    downloadBtn.style.pointerEvents = 'none';
    
    // Restaurar el botón después de 2 segundos
    setTimeout(() => {
        downloadBtn.innerHTML = originalContent;
        downloadBtn.style.pointerEvents = 'auto';
    }, 2000);
    
    // Dejar que el enlace funcione normalmente (no prevenir el comportamiento por defecto)
});