<script setup>
import { computed, watch } from "vue";
import MdrModal from "@/components/Mudur-Ui-Kit/MdrModal.vue";
import PrimaryButton from "@/components/Buttons/PrimaryButton.vue";

const props = defineProps({
  modelValue: Boolean,
  pdfUrl: {
    type: String,
    default: "",
  },
  disableReload: {
    type: Boolean,
    default: false,
  },
});

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

const printPDF = () => {
  const iframe = document.querySelector("#barcode-pdf");
  if (iframe) {
    iframe.contentWindow.focus();
    iframe.contentWindow.print();
  }
};

watch(componentValue, (newVal, oldVal) => {
  if (props.disableReload) return;
  if (!newVal && oldVal) {
    window.location.reload();
  }
});
</script>

<template>
  <MdrModal v-model="componentValue" size="md:size-4/5 lg:size-3/5">
    <template #title>{{ $t("barcode_prinout") }}</template>
    <div v-if="pdfUrl">
      <iframe
        id="barcode-pdf"
        :src="pdfUrl"
        width="100%"
        height="500px"
        @load="printPDF"
      ></iframe>
    </div>
    <div v-else>
      <div>{{ pdfUrl }}</div>
    </div>
    <template #actions>
      <div class="flex gap-3 justify-end w-full">
        <div class="flex gap-2">
          <PrimaryButton @click="componentValue = !componentValue">{{
            $t("ok")
          }}</PrimaryButton>
        </div>
      </div>
    </template>
  </MdrModal>
</template>
