const userSelect = {
  user: {
    valueField: "id",
    searchField: "name",
    options: [], // Initialize empty array for options
    placeholder: "Select the user",
    plugins: ['remove_button'],
    onDelete: function (values) {
    },
    render: {
      option: function (data, escape) {
        if (!data.name) {
          // console.log(data)
          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>
                                <span class="text-xs opacity-80">${escape(data.email)}</span>
                            </div>
                        </div>`;
      },
      item: function (data, escape) {
        if (!data.name) {
          console.error("Invalid data for item:", data);
          return "";
        }
         return `<span class="badge rounded-lg bg-primary dark:bg-accent text-white px-2 m-1 mr-2 py-2">
                            <span class="mx-2">${escape(data.name)}</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 };