import { modalCreateStage } from "../pages/stages/components/modals/ModalAdd.js";
import { createStage } from "../hooks/stages/createStage.js";
import { getStage } from "../hooks/stages/getStage.js";
import renderStageDetails from "../pages/project/components/DetailStage.js";
import { modalUpdateStage, modalUpdateStageTrafficLight } from "../pages/stages/components/modals/ModalEdit.js";
import { updateStage, updateTrafficLight } from "../hooks/stages/updateStage.js";
import { formatDateForInput } from "../utils/formatter.js";
import { removeStage } from "../hooks/stages/removeStage.js";

export default class Stage {
    constructor(projectId) {
        this.projectId = projectId;
    }

    addStageToDOM(stage, parentId = null) {
        const statusColors = {
            'rojo': '#dc2626',
            'amarillo': '#ca8a04',
            'verde': '#16a34a'
        };
        const color = statusColors[stage.status_traffic_light] || '#27272a';

        const stageHTML = `
            <div class="stage-item flex flex-col gap-1">
                <div data-parent-id="${stage.id}" class="flex items-center gap-2 stage-header justify-between px-2 pr-4 rounded-lg text-zinc-800 hover:bg-[#eeedfa] transition-all ease-in-out cursor-pointer" data-stage-id="${stage.id}" style="margin-left:${parentId ? '10px' : '0px'}">
                    <div class="stage-title flex items-center gap-1 overflow-hidden whitespace-nowrap text-ellipsis max-w-[calc(100%-4rem)]">
                        <span class="w-4"></span>
                        <svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='currentColor' style='color: ${color};' class='h-4 w-4'>
                            <path d='M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z'/>
                        </svg>
                        <span class="ml-1 font-medium">${stage.name}</span>
                    </div>
                    <button class="add-stage-btn ml-auto text-xs text-[#393784] cursor-pointer flex-shrink-0" data-parent-id="${stage.id}" title="Agregar etapa hija">+ Etapa</button>
                </div>
            </div>
        `;

        if (parentId) {
            // Buscar la etapa padre
            const parentStageItem = document.querySelector(`[data-stage-id="${parentId}"]`)?.closest('.stage-item');
            if (parentStageItem) {
                let childrenContainer = parentStageItem.querySelector('.stage-children');
                
                // Si no existe el contenedor de hijos, crearlo
                if (!childrenContainer) {
                    childrenContainer = document.createElement('div');
                    childrenContainer.className = 'stage-children';
                    parentStageItem.appendChild(childrenContainer);
                    
                    // Mostrar la flecha del padre
                    const parentHeader = parentStageItem.querySelector('.stage-header');
                    const emptySpan = parentHeader.querySelector('.stage-title span.w-4');
                    if (emptySpan) {
                        emptySpan.outerHTML = '<svg class="h-4 w-4 stage-toggle cursor-pointer transition-transform rotate-90" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>';
                    }
                }
                
                childrenContainer.insertAdjacentHTML('beforeend', stageHTML);
            }
        } else {
            // Agregar como raíz
            const stageTree = document.querySelector('#stage-tree ul');
            if (stageTree) {
                stageTree.insertAdjacentHTML('beforeend', stageHTML);
            }
        }
    }

    async add(parentId = null) {
        modalCreateStage.onOpen = () => {
            document.getElementById('SubmitStage')?.addEventListener('click', async (e) => {
                const newStage = await createStage(parentId, this.projectId);
                if(newStage){
                    modalCreateStage.close();
                    this.addStageToDOM(newStage, parentId);
                }
            });
        }
        modalCreateStage.open();
    }

    async showDetails(stageId){
        const response = await getStage(stageId);
        renderStageDetails(response?.data);

        document.getElementById("modal_editStage")?.addEventListener("click", () => {
            modalUpdateStage.onOpen = () => {
                document.getElementById('SubmitStage')?.addEventListener('click', async (e) => {
                    const updated = await updateStage(stageId);
                    if(updated){
                        modalUpdateStage.close();
                        // Recargar los detalles de la etapa con los datos actualizados
                        const updatedResponse = await getStage(stageId);
                        if(updatedResponse?.data) {
                            renderStageDetails(updatedResponse.data);
                            
                            // Actualizar el nombre en el árbol
                            const stageHeader = document.querySelector(`[data-stage-id="${stageId}"]`);
                            if(stageHeader) {
                                const nameSpan = stageHeader.querySelector('.stage-title span.ml-1');
                                if(nameSpan) {
                                    nameSpan.textContent = updatedResponse.data.name;
                                }
                            }
                        }
                    }
                });
            }

            modalUpdateStage.open({
                stage: response?.data,
                initial: formatDateForInput(response?.data?.project?.start_date?.date),
                limit: formatDateForInput(response?.data?.project?.end_date?.date)
            });
        });
    }

    async remove(stageId){
        if(!confirm('¿Estás seguro de que deseas eliminar esta etapa? Esta acción no se puede deshacer.')) return;

        const response = await removeStage(stageId);
        if(response){
            // Eliminar la etapa del árbol
            const stageItem = document.querySelector(`[data-stage-id="${stageId}"]`)?.closest('.stage-item');
            if(stageItem) {
                stageItem.remove();
            }
            
            // Limpiar el panel de detalles
            const stageDetails = document.getElementById('stage-details');
            if(stageDetails) {
                stageDetails.innerHTML = `
                    <div class="flex flex-col items-center justify-center h-full text-center p-8">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-16 h-16 text-zinc-400 mb-4">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 9.776c.112-.017.227-.026.344-.026h15.812c.117 0 .232.009.344.026m-16.5 0a2.25 2.25 0 0 0-1.883 2.542l.857 6a2.25 2.25 0 0 0 2.227 1.932H19.05a2.25 2.25 0 0 0 2.227-1.932l.857-6a2.25 2.25 0 0 0-1.883-2.542m-16.5 0V6A2.25 2.25 0 0 1 6 3.75h3.879a1.5 1.5 0 0 1 1.06.44l2.122 2.12a1.5 1.5 0 0 0 1.06.44H18A2.25 2.25 0 0 1 20.25 9v.776" />
                        </svg>
                        <p class="text-zinc-500 text-lg">Selecciona una etapa para ver sus detalles</p>
                    </div>
                `;
            }
        }
    }

    async updateLightTraffic(stageId, color){
        modalUpdateStageTrafficLight.onOpen = () => {
            document.getElementById("SubmitStageTrafficLight")?.addEventListener("click", async (e) => {
                const status = document.getElementById("status_traffic_light")?.value;
                const updated = await updateTrafficLight(stageId, status);
                if(updated){
                    modalUpdateStageTrafficLight.close();
                    
                    // Actualizar el color del semáforo en los detalles
                    const statusColors = {
                        'rojo': 'bg-red-500',
                        'amarillo': 'bg-yellow-500',
                        'verde': 'bg-green-500'
                    };
                    const colorClass = statusColors[status] || 'bg-gray-500';
                    
                    // Actualizar en el panel de detalles
                    const trafficLightSpan = document.querySelector('#stage-details .rounded-full');
                    if(trafficLightSpan) {
                        trafficLightSpan.className = `p-2 ${colorClass} rounded-full border border-zinc-300`;
                    }
                    
                    // Actualizar el icono en el árbol
                    const statusColorsIcon = {
                        'rojo': '#dc2626',
                        'amarillo': '#ca8a04',
                        'verde': '#16a34a'
                    };
                    const iconColor = statusColorsIcon[status] || '#27272a';
                    
                    const stageHeader = document.querySelector(`[data-stage-id="${stageId}"]`);
                    if(stageHeader) {
                        const folderIcon = stageHeader.querySelector('svg[viewBox="0 0 24 24"]');
                        if(folderIcon) {
                            folderIcon.style.color = iconColor;
                        }
                    }
                }
            })
        };

        modalUpdateStageTrafficLight.open({ 
            stage: {
                id: stageId,
                status_traffic_light: color
            }
         });
    }
}