document.addEventListener('DOMContentLoaded', async () => {
  const roleSelect = document.getElementById('roleSelect');
  const permissionsContainer = document.getElementById('permissionsContainer');
  let roles;
  let permissions;

  // Fetch all roles
  const fetchRoles = async () => {
    try {
      const response = await fetch('/api/role'); // API endpoint for fetching roles
      if (!response.ok) {
        throw new Error('Failed to fetch roles');
      }
      return await response.json();
    } catch (error) {
      console.error('Error fetching roles:', error);
      alert('Could not load roles. Please try again later.');
      return [];
    }
  };

  // Render roles in the dropdown
  const renderRoles = (roles) => {
    roleSelect.innerHTML = '<option value="" disabled selected>Select a Role</option>';
    roles.forEach((role) => {
      const option = document.createElement('option');
      option.value = role._id;
      option.textContent = role.name;
      roleSelect.appendChild(option);
    });
  };

  // Render categorized permissions with toggle switches
  const renderPermissions = (permissionsCategories, selectedPermissions = []) => {
    permissionsContainer.innerHTML = ''; // Clear previous permissions

    Object.keys(permissionsCategories).forEach((categoryKey) => {
      const category = permissionsCategories[categoryKey];

      // Create category container
      const categoryDiv = document.createElement('div');
      categoryDiv.classList.add('permissions-category');

      const categoryTitle = document.createElement('h4');
      categoryTitle.textContent = category.name;
      categoryDiv.appendChild(categoryTitle);

      // Render permissions for each category
      const permissionsGrid = document.createElement('div');
      permissionsGrid.classList.add('permissions-grid');

      Object.keys(category.permissions).forEach((permissionKey) => {
        const permissionDiv = document.createElement('div');
        permissionDiv.classList.add('permission-item');

        const checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.id = `perm-${permissionKey}`;
        checkbox.value = permissionKey;
        checkbox.checked = selectedPermissions.includes(permissionKey);

        const label = document.createElement('label');
        label.htmlFor = `perm-${permissionKey}`;
        label.textContent = category.permissions[permissionKey];

        // Toggle switch wrapper
        const switchWrapper = document.createElement('label');
        switchWrapper.classList.add('switch');
        const slider = document.createElement('span');
        slider.classList.add('slider');

        switchWrapper.appendChild(checkbox);
        switchWrapper.appendChild(slider);

        permissionDiv.appendChild(switchWrapper);
        permissionDiv.appendChild(label);
        permissionsGrid.appendChild(permissionDiv);
      });

      categoryDiv.appendChild(permissionsGrid);
      permissionsContainer.appendChild(categoryDiv);
    });
  };

  // Load roles on page load
  roles = await fetchRoles();
  renderRoles(roles);

  



  


   async function loadAllPermissions() {
    try {
      const response = await fetch('/api/permission/all');
      if (!response.ok) {
        throw new Error('Failed to fetch permissions');
      }
       permissions = await response.json();
  
      return permissions;
    } catch (error) {
      console.error('Error loading permissions:', error);
    }
  }

  loadAllPermissions();
  
  //console.log('Permissions out:', permissions['NEW_TRANSACTION']);
  // Load selected role permissions when a role is selected
  roleSelect.addEventListener('change', () => {
    const selectedRoleId = roleSelect.value;
    const selectedRole = roles.find((role) => role._id === selectedRoleId);
    const selectedPermissionNames = selectedRole.permission.map((p) => p.name);
    renderPermissions(permissions, selectedPermissionNames);
  });

  // Handle form submission
  const editRoleForm = document.getElementById('editRoleForm');
  editRoleForm.addEventListener('submit', async (e) => {
    e.preventDefault(); // Prevent default form submission

    // Get selected role and permissions
    const selectedRoleId = roleSelect.value;
    const selectedPermissions = Array.from(
      document.querySelectorAll('#permissionsContainer input[type="checkbox"]:checked')
    ).map((checkbox) => checkbox.value);

    if (!selectedRoleId || !selectedPermissions.length) {
      alert('Please select a role and at least one permission.');
      return;
    }

    // Prepare payload
    const payload = {
      roleId: selectedRoleId,
      permissionNames: selectedPermissions,
    };

    try {
      // Send PUT request to update role
      const response = await fetch(`/api/role/${selectedRoleId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      });

      if (!response.ok) {
        throw new Error('Failed to update role');
      }

      const result = await response.json();

      roles = await fetchRoles();
      renderRoles(roles);

      alert(`Role updated successfully: ${result.role.name}`);
    } catch (error) {
      console.error('Error updating role:', error);
      alert('Could not update role. Please try again later.');
    }
  });
});
