const groupSelect = {
  group: {
    valueField: "id",
    searchField: "name",
    options: [], // Initialize empty array for options
    placeholder: "",
    placeholder: "Select the group",
    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 fetchGroups = (groupSelect) => {
  return fetch('/get-groups')
    .then(response => response.json())
    .then(data => {
      if (!data.groups || !Array.isArray(data.groups)) {
        console.error("Invalid response format:", data);
        return;
      }

      groupSelect.group.options = data.groups;
    })
    .catch(error => console.error('Error fetching group data:', error));
};


export { groupSelect, fetchGroups };