const userSelect = {
  user: {
    valueField: "id",
    searchField: "username",
    options: [], // Initialize empty array for options
    placeholder: "Select the user",
    plugins: ['remove_button'],
    closeAfterSelect: true,
    onDelete: function (values) {
    },
    render: {
      option: function (data, escape) {
        if (!data.username || !data.email) {
          console.error("Invalid data for option:", data);
          return "";
        }
        return `<div class="flex space-x-3">
                            <div class="flex flex-col">
                                <span>${escape(data.username)}</span>
                                <span class="text-xs opacity-80">${escape(data.email)}</span>
                            </div>
                        </div>`;
      },
      item: function (data, escape) {
        if (!data.username) {
          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.username)}</span>
                        </span>`;
      },
    },
  },

};

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

      userSelect.user.options = data.users;
    })
    .catch(error => console.error('Error fetching user data:', error));
};


export { userSelect, fetchUsers };