import { addEvents, getModifiedRows } from '../../common/common.js';
import userService from '../../apis/user-api.js';

let users = [];

document.addEventListener('DOMContentLoaded', () => {
    fetchDataAndRender();
    setupEventListeners();
    manageTooltips.init();
});

const setupEventListeners = () => {
    const eventMap = {
        'searchForm': { event: 'submit', handler: fetchDataAndRender },
        'updateUserBtn': { event: 'click', handler: updateUser }
    };
    addEvents(eventMap);
};

const fetchDataAndRender = async () => {
    const searchParams = new URLSearchParams(new FormData(document.getElementById('searchForm')));
    users = await userService.getUsers(searchParams);
    updateTable(users);
};

const updateTable = (users) => {
    const tableBody = document.querySelector('tbody');
    tableBody.innerHTML = users.map(user => `
        <tr data-key="${user.id}">
            <td class="align-middle">${user.userId}</td>
            <td class="align-middle">${user.userName}</td>
            <td class="align-middle">${user.email}</td>
            <td class="align-middle">
                <select id="userRole-${user.id}" class="form-select form-select-sm" ${USER_INFO.userId === user.userId ? 'disabled' : ''}>
                    ${ROLES.length > 0 ? ROLES.map(role => `
                        <option value="${role}" ${user.userRole === role ? 'selected' : ''}>${role}</option>
                    `).join('') : '<option value=""></option>'}
                </select>
            </td>
            <td class="align-middle">
                <input id="approved-${user.id}" type="checkbox" ${user.approved ? 'checked' : ''} class="form-check-input" ${USER_INFO.userId === user.userId ? 'disabled' : ''}>
            </td>
            <td class="align-middle">
            ${USER_INFO.userId !== user.userId ? `
                <button class="btn btn-sm btn-outline-danger delete-btn" data-id="${user.id}" title="사용자 삭제">
                    <i class="bi bi-trash"></i>
                </button>
            ` : ''}
            </td>
        </tr>
    `).join('');

    const eventMap = {'.delete-btn': { event: 'click', handler: deleteUser }};
    addEvents(eventMap);
};

const updateUser = async () => {
    const confirmUpdate = confirm('회원정보를 수정하시겠습니까?');
    if (confirmUpdate) {
        const updatedUsers = Array.from(document.querySelectorAll('tbody tr')).map(row => {
            const id = row.dataset.key;
            const selectElement = row.querySelector(`#userRole-${id}`);
            const checkboxElement = row.querySelector(`#approved-${id}`);
            const userRole = selectElement ? selectElement.value : null;
            const isApproved = checkboxElement ? checkboxElement.checked : false;
            return {
                id: id,
                userRole: userRole,
                approved: isApproved
            };
        });

        await userService.changeRoleApprove(getModifiedRows(users, updatedUsers, "id"));
        alert('회원정보가 수정 되었습니다.');
        manageTooltips.hideAll();
        fetchDataAndRender();
    }
};

const deleteUser = async (e) => {
    const confirmDelete = confirm('사용자를 삭제하시겠습니까?');
    if (confirmDelete) {
        const { id } = e.target.closest('button').dataset;
        await userService.deleteUser(id);
        alert('사용자가 삭제되었습니다.');
        fetchDataAndRender();
    }
};

const manageTooltips = {
    init: () => {
        document.querySelectorAll('[data-bs-toggle="tooltip"]')
            .forEach(el => new bootstrap.Tooltip(el));
    },
    hideAll: () => {
        const tooltip = bootstrap.Tooltip.getInstance('#updateUserBtn');
        setTimeout(() => tooltip.hide(), 100);
    }
};