/**
 * Users — Plataforma Ganadera
 * Gestión de usuarios, roles y permisos del sistema
 */
const Users = {
    allUsers: [],
    searchTerm: '',
    roleFilter: '',

    async init() {
        this.bindEvents();
        await Promise.all([this.loadUsers(), this.loadRoles()]);
    },

    bindEvents() {
        $('#userForm').on('submit', (e) => { e.preventDefault(); this.save(); });

        // Search users
        $(document).on('input', '#userSearch', App.debounce(() => {
            this.searchTerm = $('#userSearch').val().toLowerCase();
            this.filterAndRender();
        }, 250));

        // Filter by role
        $(document).on('change', '#userRoleFilter', () => {
            this.roleFilter = $('#userRoleFilter').val();
            this.filterAndRender();
        });
    },

    async loadUsers() {
        try {
            const res = await API.get('/users?per_page=200');
            this.allUsers = res.data || [];
            this.filterAndRender();
        } catch(e) { $('#usersBody').html('<tr><td colspan="6">Error al cargar</td></tr>'); }
    },

    filterAndRender() {
        let users = this.allUsers;

        if (this.searchTerm) {
            users = users.filter(u =>
                (u.first_name + ' ' + u.last_name).toLowerCase().includes(this.searchTerm) ||
                (u.username || '').toLowerCase().includes(this.searchTerm) ||
                (u.email || '').toLowerCase().includes(this.searchTerm)
            );
        }

        if (this.roleFilter) {
            users = users.filter(u => String(u.role_id) === String(this.roleFilter));
        }

        this.renderUsers(users);
    },

    renderUsers(users) {
        if (!users.length) {
            $('#usersBody').html('<tr><td colspan="6" class="text-center text-muted"><div class="empty-state"><p>Sin usuarios encontrados</p></div></td></tr>');
            return;
        }

        const html = users.map(u => {
            const fullName = `${u.first_name} ${u.last_name}`;
            const initials = (u.first_name?.[0] || '') + (u.last_name?.[0] || '');
            const lastLogin = u.last_login ? App.timeAgo(u.last_login) : 'Nunca';

            return `<tr>
                <td>
                    <div style="display:flex;align-items:center;gap:0.6rem">
                        <div class="user-avatar-sm">${initials.toUpperCase()}</div>
                        <div>
                            <strong>${fullName}</strong>
                            <div style="font-size:0.78rem;color:var(--text-muted)">@${u.username}</div>
                        </div>
                    </div>
                </td>
                <td>${u.email}</td>
                <td><span class="role-badge">${u.role_name || '—'}</span></td>
                <td><span class="user-status user-${u.is_active ? 'active' : 'inactive'}">
                    <span class="status-dot"></span>${u.is_active ? 'Activo' : 'Inactivo'}
                </span></td>
                <td>${lastLogin}</td>
                <td>
                    <div class="action-btns">
                        <button class="btn btn-sm btn-ghost" onclick="Users.edit(${u.id})" title="Editar">${Icons.edit(14)}</button>
                        <button class="btn btn-sm btn-ghost" onclick="Users.resetPassword(${u.id})" title="Cambiar contraseña">${Icons.key ? Icons.key(14) : '🔑'}</button>
                        <button class="btn btn-sm btn-ghost" onclick="Users.toggleStatus(${u.id}, ${u.is_active})" title="${u.is_active ? 'Desactivar' : 'Activar'}">
                            ${u.is_active ? Icons.lock(14) : Icons.unlock(14)}
                        </button>
                    </div>
                </td>
            </tr>`;
        }).join('');
        $('#usersBody').html(html);
    },

    async loadRoles() {
        try {
            const res = await API.get('/roles');
            const roles = res.data || [];

            // Populate role select in user create/edit form
            $('#userRole').html(roles.map(r => `<option value="${r.id}">${r.name}</option>`).join(''));

            // Populate role filter dropdown
            const filterSelect = document.getElementById('userRoleFilter');
            if (filterSelect) {
                filterSelect.innerHTML = '<option value="">Todos los roles</option>' +
                    roles.map(r => `<option value="${r.id}">${r.name}</option>`).join('');
            }

            // Render roles table
            const html = roles.map(r => {
                const permCount = r.permission_count || r.permissions?.length || '—';
                return `<tr>
                    <td><strong>${r.name}</strong><div style="font-size:0.75rem;color:var(--text-muted)">${r.slug || ''}</div></td>
                    <td>${r.description || '—'}</td>
                    <td><span class="chip chip-sm">${permCount}</span></td>
                    <td>
                        <button class="btn btn-sm btn-ghost" onclick="Users.viewRolePerms(${r.id})" title="Ver permisos">${Icons.eye(14)}</button>
                    </td>
                </tr>`;
            }).join('');
            $('#rolesBody').html(html || '<tr><td colspan="4" class="text-center text-muted">Sin roles</td></tr>');
        } catch(e) {}
    },

    showCreateModal() {
        $('#userModalTitle').text('Nuevo Usuario');
        $('#userForm')[0].reset();
        $('#userId').val('');
        $('#passwordGroup').show();
        $('#userPassword').attr('required', true);
        Modal.open('userModal');
    },

    async edit(id) {
        try {
            const res = await API.get(`/users/${id}`);
            const u = res.data;
            $('#userModalTitle').text('Editar Usuario');
            $('#userId').val(u.id);
            $('#userFirst').val(u.first_name);
            $('#userLast').val(u.last_name);
            $('#userEmail').val(u.email);
            $('#userUsername').val(u.username);
            $('#userRole').val(u.role_id);
            $('#userPhone').val(u.phone || '');
            $('#passwordGroup').show();
            $('#userPassword').removeAttr('required').val('');
            Modal.open('userModal');
        } catch(e) { Toast.danger('Error al cargar usuario'); }
    },

    async save() {
        const id = $('#userId').val();
        const data = {
            first_name: $('#userFirst').val(),
            last_name: $('#userLast').val(),
            email: $('#userEmail').val(),
            username: $('#userUsername').val(),
            role_id: $('#userRole').val(),
            phone: $('#userPhone').val() || null,
        };
        const password = $('#userPassword').val();
        if (password) data.password = password;
        if (!id && !password) { Toast.warning('La contraseña es obligatoria para usuarios nuevos'); return; }

        try {
            if (id) await API.put(`/users/${id}`, data);
            else await API.post('/users', data);
            Modal.close('userModal');
            Toast.success(id ? 'Usuario actualizado exitosamente' : 'Usuario creado exitosamente');
            this.loadUsers();
        } catch(e) {
            const msg = e?.data?.message || 'Error al guardar usuario';
            Toast.danger(msg);
        }
    },

    async toggleStatus(id, currentActive) {
        const action = currentActive ? 'desactivar' : 'activar';
        if (!confirm(`¿Deseas ${action} este usuario?`)) return;
        try {
            if (currentActive) {
                await API.put(`/users/${id}/deactivate`);
            } else {
                await API.put(`/users/${id}/activate`);
            }
            Toast.success(`Usuario ${currentActive ? 'desactivado' : 'activado'}`);
            this.loadUsers();
        } catch(e) { Toast.danger('Error al cambiar estado'); }
    },

    async resetPassword(id) {
        const html = `<div class="form-group">
            <label class="form-label">Nueva contraseña</label>
            <input type="password" class="form-input" id="newPwdInput" required minlength="6">
        </div>
        <div class="form-group">
            <label class="form-label">Confirmar contraseña</label>
            <input type="password" class="form-input" id="confirmPwdInput" required>
        </div>`;

        try {
            await Modal.confirm(html, 'Cambiar Contraseña');
            const pwd = $('#newPwdInput').val();
            const confirm = $('#confirmPwdInput').val();
            if (!pwd || pwd.length < 6) { Toast.warning('La contraseña debe tener al menos 6 caracteres'); return; }
            if (pwd !== confirm) { Toast.warning('Las contraseñas no coinciden'); return; }

            await API.put(`/users/${id}`, { password: pwd });
            Toast.success('Contraseña actualizada');
        } catch(e) {
            // User cancelled
        }
    },

    async viewRolePerms(roleId) {
        try {
            const res = await API.get(`/roles/${roleId}`);
            const role = res.data;
            const perms = role.permissions || [];

            let html = `<h4 style="margin-bottom:0.75rem">${role.name}</h4>`;
            if (role.description) html += `<p style="color:var(--text-muted);margin-bottom:1rem">${role.description}</p>`;

            if (perms.length) {
                // Group permissions by module
                const grouped = {};
                perms.forEach(p => {
                    const module = (p.slug || p.name || '').split('.')[0] || 'general';
                    if (!grouped[module]) grouped[module] = [];
                    grouped[module].push(p);
                });

                html += '<div style="max-height:400px;overflow-y:auto">';
                Object.entries(grouped).forEach(([module, items]) => {
                    html += `<div style="margin-bottom:0.75rem"><strong style="text-transform:capitalize;color:var(--color-primary)">${module}</strong>`;
                    html += '<div style="display:flex;flex-wrap:wrap;gap:0.35rem;margin-top:0.35rem">';
                    items.forEach(p => {
                        html += `<span class="chip chip-sm">${p.name || p.slug}</span>`;
                    });
                    html += '</div></div>';
                });
                html += '</div>';
            } else {
                html += '<p class="text-muted">Sin permisos asignados</p>';
            }

            Modal.confirm(html, 'Cerrar').catch(() => {});
        } catch(e) { Toast.danger('Error al cargar permisos'); }
    }
};

$(document).ready(() => Users.init());
