<script setup lang="ts">
import { ref } from 'vue';

const props = defineProps({
  username: {
    type: String,
    required: true
  },
  isAdmin: {
    type: Boolean,
    required: true
  }
})

const emit = defineEmits<{
  (e: 'delete', username: string): void
  (e: 'update', username: string, newPassword: string, newIsAdmin: boolean): void
}>()

const isEditing = ref<boolean>(false);
const editingPassword = ref<string>("");
const editingIsAdmin = ref<boolean>(false);

const editItem = () => {
  // copy isAdmin to checkbox and clean password box
  editingIsAdmin.value = props.isAdmin;
  editingPassword.value = "";
  // switch to edit mode
  isEditing.value = true;
}

const deleteItem = () => {
  emit('delete', props.username);
}

const updateItem = () => {
  const new_password = editingPassword.value;
  const new_isAdmin = editingIsAdmin.value;
  // clean editing state
  editingPassword.value = "";
  // switch to normal mode
  isEditing.value = false;
  emit('update', props.username, new_password, new_isAdmin);
}

const cancelUpdateItem = () => {
  // clean editing state
  editingPassword.value = "";
  // switch to normal mode
  isEditing.value = false;
}
</script>

<template>
  <div class="paperbox-item card">
    <div class="paperbox-item-multiline-words">
      <div class="control" style="display: flex; flex-flow: row; align-items: center;">
        <div v-show="isAdmin" class="icon is-small" style="margin-right: 1rem;">
          <font-awesome-icon icon="fas fa-wrench"></font-awesome-icon>
        </div>
        <div>{{ username }}</div>
      </div>
      <div v-show="isEditing" class="field">
        <label class="label">New Password</label>
        <div class="control">
          <input v-model="editingPassword" class="input" type="password">
        </div>
      </div>
      <div v-show="isEditing" class="field">
        <label class="checkbox">
          <input v-model="editingIsAdmin" type="checkbox"><span>Is Admin</span>
        </label>
      </div>
    </div>

    <div class="paperbox-item-icon control" v-show="!isEditing" @click="editItem">
      <a class="button"><span class="icon is-small"><font-awesome-icon icon="fas fa-pen"></font-awesome-icon></span></a>
    </div>
    <div class="paperbox-item-icon control" v-show="!isEditing" @click="deleteItem">
      <a class="button"><span class="icon is-small"><font-awesome-icon
            icon="fas fa-trash"></font-awesome-icon></span></a>
    </div>

    <div class="paperbox-item-icon control" v-show="isEditing" @click="updateItem">
      <a class="button"><span class="icon is-small"><font-awesome-icon
            icon="fas fa-check"></font-awesome-icon></span></a>
    </div>
    <div class="paperbox-item-icon control" v-show="isEditing" @click="cancelUpdateItem">
      <a class="button"><span class="icon is-small"><font-awesome-icon
            icon="fas fa-times"></font-awesome-icon></span></a>
    </div>
  </div>
</template>

<style scoped></style>
