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

let users = [];

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

const setupEventListeners = () => {
    document.getElementById('searchForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        fetchDataAndRender();
    });
    document.getElementById('updateUserBtn').addEventListener('click', () => {
        const confirmUpdate = confirm('회원정보를 수정하시겠습니까?');
        if (confirmUpdate) {
            updateUser();
        }
    });
};

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">
                    ${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">
            </td>
            <td class="align-middle">
                <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('');

    document.querySelectorAll('.delete-btn').forEach(btn => btn.addEventListener('click', (e) => {
        const confirmUpdate = confirm('회원정보를 삭제하시겠습니까?');
        if (confirmUpdate) {
            const {id} = e.target.closest('button').dataset;
            deleteUser(id);
        }
    }));
};

const updateUser = async () => {
    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('회원정보가 수정 되었습니다.');
    fetchDataAndRender();
};

const deleteUser = async (id) => {
    await userService.deleteUser(id);
    alert('사용자가 삭제되었습니다.');
    fetchDataAndRender();
};