<template>
  <v-container ref="printContent" fluid style="overflow-y: auto">
    <v-row no-gutters class="main-container">
      <v-col v-for="(card, idx) in accessCards" :key="idx" cols="auto">
        <div class="qr-box">
          <p><strong>Access Level:</strong> {{ card.accessLevel }}</p>
          <p><strong>HID NO:</strong> {{ card.cardNumber }}</p>
          <img :src="card.qrDataImage" alt="QR Code" />
          <p><strong>Card No.:</strong> C{{ card.qrTagCardNo }}</p>
        </div>
      </v-col>
    </v-row>
  </v-container>
</template>

<script setup lang="ts">
import type { ComponentPublicInstance } from "vue";

defineProps<{ accessCards?: any[] }>();
defineEmits(["close"]);

const printContent = ref<HTMLElement | null>(null);

async function downloadPDF() {
  const html2pdf = (await import("html2pdf.js")).default;
  const component = printContent.value as unknown as ComponentPublicInstance;
  const el = component.$el ?? printContent.value;

  if (!el || !(el instanceof HTMLElement)) return;

  const opt = {
    margin: 0.1,
    filename: `Access-cards-qr.pdf`,
    image: { type: "jpeg", quality: 0.98 },
    html2canvas: { scale: 2, useCORS: true },
    jsPDF: { unit: "in", format: "a4", orientation: "portrait" },
  };

  await html2pdf().set(opt).from(el).save();
}

defineExpose({ downloadPDF });
</script>

<style scoped>
.main-container {
  background-color: #fff;
  padding: 8px;
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 4px;
  width: 100%;
}
.qr-box {
  height: 3cm;
  width: 2.7cm;
  border: 1px solid #ccc;
  padding: 8px;
  text-align: center;
  page-break-inside: avoid;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
}
.qr-box p {
  font-size: 8px;
  line-height: 1.2;
}
img {
  width: 1cm;
  height: 1cm;
}
</style>
