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

const props = defineProps({
  clearAutomatically: {
    type: Boolean,
    default: false,
  },
  allowClear: {
    type: Boolean,
    default: true,
  },
  clearDelay: {
    type: Number,
    default: 5000,
  },
});

const timer_start_ms = ref(null);

const onClick = () => {
  if (props.allowClear) {
    clearErrors();
  }
};

if (props.clearAutomatically) {
  watch(() => getError('stepError'), (newValue) => {
    if (newValue && props.allowClear) {
      console.log("Clearing error after delay", props.clearDelay);
      timer_start_ms.value = Date.now();
      setTimeout(() => {
        console.log("Clearing error");
        clearErrors();
      }, props.clearDelay);
    }
  });
}

const progress_value_percent = ref(0);

const getProgressValue = () => {
  if (!timer_start_ms.value) {
    return 100;
  }
  if (!props.allowClear) {
    return 100;
  }
  if (props.clearAutomatically && timer_start_ms.value) {
    // Check if the duration has passed, if so, return 100
    if (Date.now() - timer_start_ms.value >= props.clearDelay) {
      // Clear the timer
      timer_start_ms.value = null;
      return 100;
    }
    // Calculate the progress percentage
    const elapsed = Date.now() - timer_start_ms.value;
    return Math.min((elapsed / props.clearDelay) * 100, 100);
  }
  // If not clearing automatically, return 100
  return 100;
};

const updateProgress = () => {
  progress_value_percent.value = getProgressValue();
};

// Update the progress value every 100ms
setInterval(() => {
  progress_value_percent.value = getProgressValue();
}, 10);
</script>

<template>
  <div class="mb-3" v-if="getError('stepError')">
    <div class="notification is-danger mb-0" style="border-bottom-left-radius: 0; border-bottom-right-radius: 0;">
      <button class="delete" @click="onClick" v-if="props.allowClear"></button>
      <p><strong>{{ getError('stepError') }}</strong></p>
    </div>
    <!-- Progress bar, before the error message deletes automatically -->
    <div class="is-fixed-bottom has-text-centered mt-0" style="border-bottom-left-radius: 6px; border-bottom-right-radius: 6px;">
      <progress
          class="progress is-danger"
          style="border-radius: 0 0 6px 6px;"
          :value="progress_value_percent"
          :max="100"
      ></progress>
    </div>
  </div>
</template>

<style scoped>

</style>