import { readJson } from './readJson.js';

document.addEventListener('DOMContentLoaded', async function() {
    const loadProjects = async () => {
        try {
            const data = await readJson('../data/projects.json');
            return data;
        } catch (error) {
            console.error('Erreur lors du chargement des projets :', error);
            return [];
        }
    }

    // ===* ACTIONS SUR LA PAGE *===
    const section = document.querySelector('section');
    const divProjectsGrid = document.querySelector('.projects-grid');
    const createProjectButton = document.querySelector('[data-id="creation-project-btn"]');
    const divCreateProject = document.querySelector('.form-project');
    const sectionProjects = document.querySelector('[data-id="projects"]');

    if (divProjectsGrid) {
        const data = await loadProjects();
        
        if (data) {
            const projects = Object.values(data);

            console.log('Projets :', projects);
            projects.forEach(project => {
                let state = 'Actif';
                if (!project.active) {
                    state = 'Inactif';
                } else {
                    state = 'Actif';
                }

                const projectDiv = document.createElement('div');
                
                projectDiv.className = 'card-projects';
                projectDiv.innerHTML = `
                    <div class="card-title">
                        <h3>${project.type}</h3>
                    </div>
                    <div class="action-btn">
                        <button class="btn-small btn-danger" data-id="delete-project" data-project-id="${project.id}">Supprimer</button>
                        <button class="btn-small btn-warning" data-id="edit-project" data-project-id="${project.id}">Modifier</button>
                    </div>
                    <p>Etat : ${state}</p>
                    <h3>${project.name}</h3>
                    <p>${project.description}</p>
                    ${project.technologies && project.technologies.length > 0 ? `
                    <div class="card-tags">
                        ${project.technologies.map(tech => `<span class="tag">${tech}</span>`).join('')}
                    </div>` : ''}
                    ${project.link ? `<center><a href="${project.link}" target="_blank" class="btn-primary">Voir le projet</a></center>` : ''}
                `;
                divProjectsGrid.appendChild(projectDiv);

                const deleteButton = projectDiv.querySelector('[data-id="delete-project"]');
                const editButton = projectDiv.querySelector('[data-id="edit-project"]');

                deleteButton.addEventListener('click', async () => {
                    const confirmDelete = confirm(`Êtes-vous sûr de vouloir supprimer le projet "${project.name}" ?`);
                    if (confirmDelete) {
                        try {
                            window.location.href = `./?page=delete-project&id=${project.id}`;
                        } catch (error) {
                            console.error('Erreur lors de la suppression du projet :', error);
                        }
                    }
                });

                editButton.addEventListener('click', () => {
                    const projectId = editButton.getAttribute('data-project-id');
                    const projectToEdit = projects.find(p => p.id === projectId);
                    
                    if (projectToEdit) {
                        // Remplir le formulaire avec les données du projet à modifier
                        document.getElementById('project-type').value = projectToEdit.type || '';
                        document.getElementById('project-name').value = projectToEdit.name || '';
                        document.getElementById('project-description').value = projectToEdit.description || '';
                        document.getElementById('project-image').value = projectToEdit.image || '';
                        document.getElementById('project-start-date').value = projectToEdit.start_date || '';
                        document.getElementById('project-end-date').value = projectToEdit.end_date || '';
                        
                        // Pré-sélectionner les technologies si disponibles
                        if (projectToEdit.technologies && window.technologiesManager) {
                            window.technologiesManager.preselectTechnologies(projectToEdit.technologies);
                        }

                        // Afficher le formulaire et faire défiler vers celui-ci
                        divCreateProject.classList.remove('hidden');
                        createProjectButton.textContent = 'Fermer le formulaire';
                        createProjectButton.classList.remove('btn-success');
                        createProjectButton.classList.add('btn-danger');
                        
                        // Scroll vers le formulaire
                        divCreateProject.scrollIntoView({ behavior: 'smooth' });
                    }
                });
            });
        }

        
    }

    if(createProjectButton) {
        console.log("Create project button found");
        createProjectButton.addEventListener('click', () => {
            divCreateProject.classList.toggle('hidden');
            if( divCreateProject.classList.contains('hidden')) {
                createProjectButton.textContent = 'Ajouter projet';
                createProjectButton.classList.remove('btn-danger');
                createProjectButton.classList.add('btn-success');
                
                // Réinitialiser le formulaire
                const form = divCreateProject.querySelector('form');
                if (form) {
                    form.reset();
                    // Réinitialiser aussi les technologies
                    if (window.technologiesManager) {
                        window.technologiesManager.clearAllSelections();
                    }
                }
            }
            else {
                createProjectButton.textContent = 'Fermer le formulaire';
                createProjectButton.classList.remove('btn-success');
                createProjectButton.classList.add('btn-danger');
                
                // Scroll vers le formulaire
                divCreateProject.scrollIntoView({ behavior: 'smooth' });
            }
        })
    }
});