// JavaScript for toggling between tabs
const registerTab = document.getElementById('register-tab');
const listTab = document.getElementById('list-tab');
const registerContainer = document.getElementById('register-user-container');
const listContainer = document.getElementById('users-list-container');
const branchSelect1 = document.getElementById('branch1');
const branchesSelect = document.getElementById('branches');

let allBranches=[];
registerTab.addEventListener('click', () => {
  registerTab.classList.add('active');
  listTab.classList.remove('active');
  registerContainer.classList.add('active');
  listContainer.classList.remove('active');
});

listTab.addEventListener('click', () => {
  listTab.classList.add('active');
  registerTab.classList.remove('active');
  listContainer.classList.add('active');
  registerContainer.classList.remove('active');
});

// Fetch and populate branches in the dropdown
async function fetchBranches() {
  try {
    const companyId = sessionStorage.getItem('companyId');
    const response = await fetch(`/api/branches?companyId=${companyId}`);
    const branches = await response.json();
    allBranches=branches;
   
    // Clear existing options (except the placeholder option)
    branchSelect1.innerHTML = '<option value="">Select default branch</option>';
    branchesSelect.innerHTML='';
    // Populate the dropdown with branches
    branches.forEach((branch) => {
       // Create option for branchSelect1
  const option1 = document.createElement('option');
  option1.value = branch._id;
  option1.textContent = branch.name;

  // Create option for branchesSelect
  const option2 = document.createElement('option');
  option2.value = branch._id;
  option2.textContent = branch.name;

  // Append options to their respective selects
  branchSelect1.appendChild(option1);
  branchesSelect.appendChild(option2);
  
    });
  } catch (error) {
    console.error('Error fetching branches:', error);
  }
}

// Fetch and populate roles in the dropdown
async function fetchRoles() {
  try {
    const response = await fetch('/api/role'); // Assuming this endpoint returns all roles
    const roles = await response.json();
    const roleSelect = document.getElementById('role');

    // Clear existing options (except the placeholder option)
    roleSelect.innerHTML = '<option value="">Select a role</option>';

    // Populate the dropdown with roles
    roles.forEach((role) => {
      const option = document.createElement('option');
      option.value = role._id;
      option.textContent = role.name;
      roleSelect.appendChild(option);
    });
  } catch (error) {
    console.error('Error fetching roles:', error);
  }
}

// Call fetchBranches and fetchRoles when the page loads
fetchBranches();
fetchRoles();

// JavaScript for handling form submission (create or update user)
document.getElementById('user-form').addEventListener('submit', async (event) => {
  event.preventDefault();
  const companyId = sessionStorage.getItem('companyId');
  const userId = document.getElementById('user-id').value; // Hidden field for user ID


  const branchesSelect = document.getElementById('branches'); // Your multi-select element
  const selectedValues = Array.from(branchesSelect.selectedOptions).map(option => option.value);


  if (!selectedValues.includes( document.getElementById('branch1').value)) {
    document.getElementById('errorMessage').textContent = 
      'Error: The default branch must exist within the allowed branches.';
    return; // Stop form submission
  }
  // Clear the error message if validation passes
  document.getElementById('errorMessage').textContent = '';

  const formData = {
    username: document.getElementById('username').value,
    email: document.getElementById('email').value,
    password: document.getElementById('password').value,
    passcode: document.getElementById('passcode').value,
    companyId,
    branchId: document.getElementById('branch1').value,
    allowedBranchId:selectedValues,
    roleId: document.getElementById('role').value,
    kitchenId: document.getElementById('kitchen').value,
  };

  const url = userId ? `/api/users/${userId}` : '/api/users'; // Update if userId exists, else create
  const method = userId ? 'PUT' : 'POST'; // PUT for update, POST for create

  try {
    const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData),
    });

    if (response.ok) {
        alert(userId ? 'User updated successfully!' : 'User registered successfully!');
        document.getElementById('user-form').reset();
        document.getElementById('user-id').value = ''; // Clear user ID
        fetchUsers(); // Refresh the user list
        listTab.click();
    } else {
        // Parse backend error message
        const errorResponse = await response.json();
        alert(`Error: ${errorResponse.message || 'Failed to process request'}`);
        console.error('Response error:', errorResponse);
    }
} catch (error) {
    // Log network or unexpected errors
    console.error('Error:', error);
    alert('An unexpected error occurred. Please check the console for details.');
}

});

// Fetch and display users in the users list
async function fetchUsers() {
  try {
    const companyId = sessionStorage.getItem('companyId');
    const response = await fetch(`/api/users?companyId=${companyId}`);

    const users = await response.json();
    const tbody = document.getElementById('users-table').querySelector('tbody');
    tbody.innerHTML = '';

    users.forEach((user) => {
      const row = document.createElement('tr');
      row.innerHTML = `
        <td>${user.username}</td>
        <td>${user.email}</td>
          <td>${user.passcode}</td>
        <td>${user.companyId.name}</td>
        <td>${user.branchId ? user.branchId.name : 'N/A'}</td>
             <td>${user.kitchenId ? user.kitchenId.name : 'N/A'}</td>
        <td>${user.roleId?user.roleId.name :'N/A'}</td>
        <td>
          <button onclick="editUser('${user._id}')">Edit</button>
          <button onclick="deleteUser('${user._id}')">Delete</button>
        </td>
      `;
      tbody.appendChild(row);
    });
  } catch (error) {
    console.error('Error:', error);
  }
}

// Call fetchUsers to load the list of users when the page loads
fetchUsers();

// Edit user
async function editUser(userId) {
  try {
    const response = await fetch(`/api/users/${userId}`); // Fetch user details
    const user = await response.json();

    // Populate the form with user details
    document.getElementById('user-id').value = user._id; // Hidden field for user ID
    document.getElementById('username').value = user.username;
    document.getElementById('email').value = user.email;
    document.getElementById('passcode').value = user.passcode;
   // document.getElementById('password').value = '123456'; // Password should be re-entered
   
    document.getElementById('branch1').value = user.branchId ? user.branchId: '';
   

    // branchSelect1.innerHTML='';
    // allBranches.forEach(branch => {
    //    const option = document.createElement('option');
    //    option.value = branch._id;
    //    option.textContent = branch.name;
     
    //    // Mark as selected if the branch ID is in allowedBranchIds
    //  //  alert(user.branchId);
    //    if ((user.branchId).includes(branch._id)) {
    //      option.selected = true;
    //    }     
    //   branchSelect1.appendChild(option);
    //  });


    
    branchesSelect.innerHTML='';
   allBranches.forEach(branch => {
      const option = document.createElement('option');
      option.value = branch._id;
      option.textContent = branch.name;
    
      // Mark as selected if the branch ID is in allowedBranchIds
      if (user.allowedBranchId.includes(branch._id)) {
        option.selected = true;
      }
    
      branchesSelect.appendChild(option);
    });



    document.getElementById('role').value = user.roleId;
    document.getElementById('kitchen').value = user.kitchenId;
    // Switch to the Register tab
    registerTab.click();
  } catch (error) {
    console.error('Error fetching user details:', error);
  }
}

// Delete user
async function deleteUser(userId) {
  try {
    const response = await fetch(`/api/users/${userId}`, {
      method: 'DELETE',
    });

    if (response.ok) {
      alert('User deleted successfully!');
      fetchUsers(); // Refresh the user list
    } else {
      alert('Failed to delete user');
    }
  } catch (error) {
    console.error('Error:', error);
  }
}


async function fetchDataAndPopulate(url, selectElement) {
  try {
    const response = await fetch(url);
    const data = await response.json();
    data.forEach(item => {
      const option = document.createElement('option');
      option.value = item._id;
      option.textContent = item.name;
      selectElement.appendChild(option);
    });
  } catch (error) {
    console.error('Error loading data:', error);
  }
}

const kitchenSelect = document.getElementById('kitchen');
// Populate kitchen options
fetchDataAndPopulate('/api/kitchen', kitchenSelect);
