<template>
  <div>
    <Teleport v-if="value" to="body">
      <div
        :class="['n-modal-wrapper pkg-base-n-dialog', wrapperClass]"
        @click="onBackdropClicked"
      >
        <div
          class="n-modal-overlay n-flex n-align-center n-justify-center n-flex-column"
        >
          <div
            :class="[
              contentWrapperClass,
              'n-bg-white n-overflow-y-auto n-flex n-flex-column n-modal-card n-p-6 n-radius-md n-shadow-md',
            ]"
            :style="{ maxWidth, maxHeight }"
            @click="onClickModalBody"
          >
            <slot />
          </div>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<script>
import { defineComponent } from "vue";
import Teleport from "vue2-teleport";

export default defineComponent({
  name: "NDialog",
  components: {
    Teleport,
  },
  provide() {
    return {
      closeDialog: this.onCloseDialog,
      title: this.title,
    };
  },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    showDividers: {
      type: Boolean,
      default: true,
    },
    persistent: {
      type: Boolean,
      default: false,
    },
    wrapperClass: {
      type: String,
      default: "",
    },
    contentWrapperClass: {
      type: String,
      default: "",
    },
    title: {
      type: String,
      default: "",
    },
    maxWidth: {
      type: [Number, String],
      default: "auto",
    },
    maxHeight: {
      type: [Number, String],
      default: "auto",
    },
  },
  watch: {
    open() {
      if (this.open) {
        document.body.classList.add("n-overflow-hidden");
      } else {
        document.body.classList.remove("n-overflow-hidden");
      }
    },
  },
  methods: {
    onClickModalBody(e) {
      e.stopPropagation();
    },
    onBackdropClicked() {
      if (!this.persistent) {
        this.onCloseDialog();
      }
    },
    onCloseDialog() {
      this.$emit("input", false);
      this.$emit("close", false);
    },
  },
});
</script>
