import { createSignal, onMount } from "solid-js";
import List from "../list.jsx";
import UserService from "../../services/user-service.js";
import CreateUserModal from "../../modals/create-user-modal.jsx";
import DeleteUserModal from "../../modals/delete-user-modal.jsx";
import UserSettingsModal from "../../modals/user-settings-modal.jsx";

function UserList() {
  const [users, setUsers] = createSignal([]);

  onMount(() => {
    updateUsers();
    CreateUserModal.onUserCreated(() => updateUsers());
    UserSettingsModal.onUserUpdated(() => updateUsers());
    DeleteUserModal.onUserDeleted(() => updateUsers());
  });

  async function updateUsers() {
    let users = await UserService.getUsers();
    setUsers(users);
  }

  function handleShowUserSettings(user) {
    UserSettingsModal.setUser(user);
    UserSettingsModal.Handler.show();
  }

  function handleCreateUser() {
    CreateUserModal.setUsers(users());
    CreateUserModal.Handler.show();
  }

  function handleDeleteUser(user) {
    DeleteUserModal.setUser(user);
    DeleteUserModal.Handler.show();
  }

  return (
    <>
      <div class="d-flex flex-row justify-content-end">
        <button class="btn btn-dark me-2 mb-3" onClick={handleCreateUser}>
          <i class="bi bi-plus me-2"></i>
          New User
        </button>
      </div>
      <List
        class="h-100"
        columns={[
          { id: "username", name: "Username" },
          { id: "is_admin", name: "Admin", width: 10 },
          { id: "options", name: "Options", width: 10 },
        ]}
        items={users().map((user) => ({
          username: { text: user.getUsername() },
          is_admin: { text: user.isAdmin() ? "Yes" : "No" },
          options: {
            html: (
              <>
                <button
                  class="btn btn-outline-secondary me-2"
                  onClick={() => handleShowUserSettings(user)}
                >
                  <i class="bi bi-gear-fill"></i>
                </button>
                <button
                  class="btn btn-outline-secondary me-2"
                  onClick={() => handleDeleteUser(user)}
                >
                  <i class="bi bi-trash-fill"></i>
                </button>
              </>
            ),
          },
        }))}
      />
    </>
  );
}

export default UserList;
