<script setup>
import {defineProps, onMounted, ref} from 'vue';
import {parseError, getError} from "@/components/request/HandleGlobalError.vue";

const props = defineProps({
  onSave: Function, // Function to call when the secret key is changed
  value: String|Number, // The value of the secret key
  title: String, // The label of the select
  disabled: Boolean, // If the select is disabled
  description: String, // The description of the select
  icon: String, // The icon of the select
  color: String, // The color of the select
});

const isEditting = ref(false);

const v_model = ref(props.value);

const errorId = ref(null);

const parseErrorOnSave = (error) => {
  let unique_id = Math.random().toString(36).substring(7);
  errorId.value = unique_id;
  parseError(error, unique_id);
}


</script>

<template>
  <div class="field">
    <label class="label">{{ title }}</label>
    <!-- If the value is not set, show a warning message -->
    <div v-if="!props.value" class="message is-warning">
      <div class="message-body">
        <strong>Warning:</strong>
        The value of this field is not set. Please set the value before continuing.
      </div>
    </div>
    <div class="control">
      <div class="field has-addons">
        <div class="control is-expanded">
          <input
            class="input"
            type="text"
            v-model="v_model"
            :disabled="disabled || !isEditting"
          />
        </div>
        <div class="control">
          <a class="button is-info" @click="onSave(v_model).catch(parseErrorOnSave); isEditting = false" v-if="isEditting">
            <span class="icon">
              <i class="fas fa-save"></i>
            </span>
          </a>
          <!-- If the secret key is set, show the edit button -->
          <a class="button is-warning" @click="isEditting = !isEditting" v-else>
            <span class="icon">
              <i class="fas fa-edit"></i>
            </span>
          </a>
        </div>
      </div>
      <!-- If the errorId is set, show the error message -->
      <div v-if="errorId" class="help is-danger">
        <span v-if="getError(errorId)">ERROR: {{ getError(errorId) }}</span>
        <span v-else>Unknown error</span>
      </div>
    </div>
    <p class="help">{{ description }}</p>
  </div>
</template>

<style scoped>

</style>