import { addProjectUser } from "../hooks/projects/addProjectUser.js";
import { getProjectUser } from "../hooks/projects/getProjectUser.js";
import { removeProjectUser } from "../hooks/projects/removeProjectUser.js";
import { modalListMembers } from "../pages/project/components/modals/ModaAddEditMembers.js";

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

    async showListMembers(){
        const users = await getProjectUser(this.projectId);
        modalListMembers.onOpen = () => {
            const searchInput = document.getElementById('searchUser');
            const resultsContainer = document.getElementById('userSearchResults');
            const removeButtons = document.querySelectorAll('.remove-user-btn');

            searchInput?.addEventListener('input', () => {
                const term = searchInput.value.toLowerCase();
                resultsContainer.querySelectorAll('.add-user-item').forEach(item => {
                    const name = item.querySelector('span').textContent.toLowerCase();
                    item.style.display = name.includes(term) ? 'flex' : 'none';
                });
            });

             resultsContainer.querySelectorAll('.add-user-btn').forEach(btn => {
                btn.addEventListener('click', async (e) => {
                    e.stopPropagation();
                    const userId = btn.parentElement.dataset.userId;
                    await addProjectUser(this.projectId, userId);
                    modalListMembers.close();
                });
            });

            removeButtons.forEach(btn => {
                btn.addEventListener('click', async (e) => {
                    e.stopPropagation();
                    const userId = btn.dataset.userId;

                    if (!confirm("¿Seguro que quieres eliminar este usuario del proyecto?")) return;

                    await removeProjectUser(this.projectId, userId);
                    modalListMembers.close();
                });
            });
        }

        modalListMembers.open({ 
            users: users?.data?.users, 
            restUsers: users?.data?.restUsers
        });
    }
}