const roleSelect = {
  role: {
    valueField: "id",
    searchField: "name",
    options: [], // Initialize empty array for options
    placeholder: "",
    placeholder: "Select the role",
    plugins: ['remove_button'],
    closeAfterSelect: true,
    onDelete: function (values) {
    },
    render: {
      option: function (data, escape) {
        if (!data.name) {
          console.error("Invalid data for option:", data);
          return "";
        }
        return `<div class="flex space-x-3">
                            <div class="flex flex-col">
                                <span>${escape(data.name)}</span>
                            </div>
                        </div>`;
      },
      item: function (data, escape) {
        if (!data.name) {
          console.error("Invalid data for item:", data);
          return "";
        }
        return `<span class="badge rounded-full bg-primary dark:bg-accent text-white px-2 py-2 mb-2 mr-2">
                            <span class="mx-2">${escape(data.name)}</span>
                        </span>`;
      },
    },
  },
};

const fetchRoles = (roleSelect) => {
  return fetch('/get-roles')
    .then(response => response.json())
    .then(data => {
      if (!data.roles || !Array.isArray(data.roles)) {
        console.error("Invalid response format:", data);
        return;
      }

      roleSelect.role.options = data.roles;
    })
    .catch(error => console.error('Error fetching role data:', error));
};


export { roleSelect, fetchRoles };