<script setup>
import { computed, useSlots, watch } from "vue";
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: false,
  },
  title: {
    type: String,
    default: "",
  },
  icon: {
    type: String,
    default: "",
  },
  dismissable: {
    type: Boolean,
    default: false,
  },
  animate: {
    type: Boolean,
    default: false,
  },
});

const visible = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  },
});

watch(visible, (value) => {
  if (value) {
    emit("onShow");
    if (!props.dismissable) {
      setTimeout(() => {
        visible.value = false;
      }, 7000);
    }
  } else {
    emit("onHide");
  }
});

const emit = defineEmits(["update:modelValue", "onShow", "onHide"]);

const hasMessage = computed(() => !!useSlots().default);
const hasIcon = computed(() => !!useSlots().icon);
const hasTitle = computed(() => !!useSlots().title);
const hasActions = computed(() => !!useSlots().actions);
</script>
<template>
  <transition
    v-if="animate"
    enter-active-class="transition-all duration-300 ease-out"
    leave-active-class="transition-all duration-300 ease-in"
    enter-from-class="opacity-0 translate-x-full"
    enter-to-class="opacity-100 translate-x-0"
    leave-from-class="opacity-100 translate-x-0"
    leave-to-class="opacity-0 -translate-y-4"
  >
    <div
      v-if="visible"
      class="flex flex-col p-4 border rounded-lg"
      role="alert"
    >
      <div
        v-if="icon || hasIcon || hasTitle || title || dismissable"
        class="flex items-center gap-2"
      >
        <slot v-if="hasIcon" name="icon" />
        <component :is="icon" v-if="icon" class="w-8 h-8" />

        <slot name="title" />
        <span v-if="title" class="text-lg font-medium" v-text="title" />

        <button
          v-if="dismissable"
          type="button"
          class="ms-auto -mx-1.5 -my-1.5 rounded-lg hover:shadow-inner p-1 inline-flex items-center justify-center h-6 w-6"
          aria-label="Close"
          @click="visible = false"
        >
          <span class="sr-only">Close</span>
          <svg
            class="w-2 h-2"
            aria-hidden="true"
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 14 14"
          >
            <path
              stroke="currentColor"
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6"
            />
          </svg>
        </button>
      </div>

      <div v-if="hasMessage" class="mt-2 flex items-start break-all">
        <slot></slot>
      </div>

      <div v-if="hasActions" class="flex mt-3">
        <slot name="actions" />
      </div>
    </div>
  </transition>
</template>
