<script setup lang="ts">
  import {useLabelEditorStore} from "~/store/labelEditorStore";
  import type {Ref} from "vue";
  import DeleteConfirm from "~/components/ui/deleteConfirm.vue";
  import {Label} from "~/types/label";

  let store = useLabelEditorStore();

  const props = defineProps({
    label: {type: Object as PropType<Label>, required: true},
  });

  let edit: Ref<boolean> = ref<boolean>(false);

  let name: Ref<string | null> = ref<string | null>(JSON.parse(JSON.stringify(props.label.name)));

  function toggleEdit() {
    if (edit.value) {
      disableEdit();
    } else {
      enableEdit();
    }
  }

  function enableEdit() {
    edit.value = true;
  }

  function disableEdit() {
    name.value = JSON.parse(JSON.stringify(props.label.name));
    edit.value = false;
  }

  async function updateLabel() {
    if (name.value != null && name.value.trim().length > 0) {
      const label = new Label(props.label.id, name.value);
      await store.updateLabel(label);

      disableEdit();
    }
  }

  async function deleteLabel() {
    await store.deleteLabel(props.label.id);
  }
</script>

<template>
  <v-card>
    <v-card-title>
      <v-row style="padding-top: 10px">
        <v-text-field
            v-model.trim="name"
            :readonly="!edit"
        />

        <v-spacer />

        <v-divider vertical/>

        <DeleteConfirm
            title="Etiketten Typ löschen?"
            :disable="!edit"
            @delete="deleteLabel()"
        />

        <v-divider vertical/>

        <v-btn
            :flat="true"
            :disabled="!edit"
            :hidden="edit"
            @click="disableEdit()"
        >
          <v-icon>mdi-cancel</v-icon>
          <v-tooltip
              activator="parent"
              location="bottom"
          >
            Abbrechen
          </v-tooltip>
        </v-btn>

        <v-btn
            :flat="true"
            :disabled="!edit"
            :hidden="edit"
            @click="updateLabel()"
        >
          <v-icon>mdi-content-save</v-icon>
          <v-tooltip
              activator="parent"
              location="bottom"
          >
            Speichern
          </v-tooltip>
        </v-btn>

        <v-divider vertical/>

        <v-btn
            :flat="true"
            @click="toggleEdit();"
        >
          <v-icon>mdi-pencil</v-icon>
          <v-tooltip
              activator="parent"
              location="bottom"
          >
            Bearbeiten
          </v-tooltip>
        </v-btn>
      </v-row>
    </v-card-title>
  </v-card>
</template>

<style scoped>

</style>