<template>
  <transition
    :name="animation"
    @after-enter="afterEnter"
    @before-leave="beforeLeave"
    @after-leave="afterLeave"
  >
    <div 
      class="pui-modal-wrapper"
      v-if="!destroyed"
      v-show="isActive"
      tabindex="-1"
    >
      <div class="background" @click="close"/>
      <div class="pui-modal animation-content" :style="customStyle">
        <div class="header" :class="[type]">
          <div class="title">
            <h1>{{ title }}</h1>
            <span v-if="description">{{ description }}</span>
          </div>
          <div class="actions">
            <button 
              class="close" 
              v-if="canClose"
              @click="close"
            >
              <i class="mdi mdi-close" />
            </button>
          </div>
        </div>
        <div class="modal-content">
          <slot />
        </div>
        <div class="footer" v-if="hasFooter">
          <slot name="footer" />
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
export default {
  name: 'PModal',
  props: {
    value: Boolean,
    active: Boolean,
    type: String,
    title: String,
    description: String,
    width: {
      type: [String, Number],
      default: 700
    },
    animation: {
      type: String,
      default: 'zoom-in'
    },
    canClose: {
      type: Boolean,
      default: true
    },
    fullScreen: Boolean,
    destroyOnHide: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      isActive: this.active || false,
      newWidth: typeof this.width === 'number'
                ? this.width + 'px'
                : this.width,
      animating: !this.active,
      destroyed: !this.active
    }
  },
  methods: {
    close() {
      if (this.canClose) {
        this.$emit('close')
        this.$emit('update:active', false)
        this.$emit('update:value', false)
      }
    },
    keyPress({ key }) {
      if (this.isActive && (key === 'Escape' || key === 'Esc')) this.close()
    },
    afterEnter() {
      this.animating = false
      this.$emit('after-enter')
    },
    beforeLeave() {
      this.animating = true
    },
    afterLeave() {
      if (this.destroyOnHide) {
        this.destroyed = true
      }
      this.$emit('after-leave')
    },
  },
  watch: {
    active(value) {
      this.isActive = value
    },
    isActive(value) {
      if (value) this.destroyed = false
    },
  },
  created() {
    if (typeof window !== 'undefined') {
      document.addEventListener('keyup', this.keyPress)
    }
  },
  beforeDestroy() {
    if (typeof window !== 'undefined') {
      document.removeEventListener('keyup', this.keyPress)
    }
  },
  computed: {
    hasFooter() {
      return !!this.$slots.footer
    },
    customStyle() {
      return { width: this.newWidth }
    }
  }
}
</script>