<template>
  <transition :name="animation">
    <div class="pui-modal-wrapper" v-if="isActive">
      <div class="background" @click="close" />
      <div class="pui-dialog animation-content">
        <div class="title" v-if="title">
          <span class="pui-text" :class="type">
            <p-icon v-if="icon" :icon="icon" class="mr-2" />
          </span>
          {{ title }}
        </div>
        <div class="dialog-content">
          <template v-if="$slots.default">
            <slot />
          </template>
          <template v-else>
            <div v-html="message" />
          </template>
        </div>
        <div class="footer">
          <p-button 
            v-if="canCancel"
            :secondary="cancelSecondary"
            :type="cancelType"
            class="mr-20"
            @click="cancel">{{ cancelText }}</p-button>
          <p-button
            @click="confirm"
            :type="type"
            ref="confirmButton">{{ confirmText }}</p-button>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
import { removeElement } from "../../utils/helpers";

export default {
  name: "PDialog",
  props: {
    title: String,
    message: String,
    icon: String,
    type: String,
    animation: {
      type: String,
      default: 'zoom-in'
    },
    confirmText: {
      type: String,
      default: "OK",
    },
    cancelText: {
      type: String,
      default: "Cancel",
    },
    cancelType: {
      type: String,
      default: 'is-info'
    },
    cancelSecondary:{
      type: Boolean,
      default: true
    },
    canCancel: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      isActive: false,
    };
  },
  methods: {
    close() {
      this.isActive = false;
      this.$emit("close", this.prompt);

      setTimeout(() => {
        this.$destroy();
        removeElement(this.$el);
      }, 150);
    },
    cancel() {
      this.$emit("cancel");
      this.close();
    },
    confirm() {
      this.$emit("confirm");
      this.close();
    },
  },
  beforeMount() {
    if (typeof window !== "undefined") {
      this.$nextTick(() => {
        const container = document.body;
        container.appendChild(this.$el);
      });
    }
  },
  mounted() {
    this.isActive = true;

    this.$nextTick(() => {
      this.$refs.confirmButton.$el.focus();
    });
  },
};
</script>