<template>
  <v-dialog :model-value="modelValue" max-width="940" scrollable @update:model-value="$emit('update:modelValue', $event)">
    <v-card>
      <v-card-title class="d-flex align-center">
        <span>Print asset labels</span>
        <v-spacer />
        <v-select
          v-model="format"
          :items="formatItems"
          density="compact"
          hide-details
          label="Symbology"
          style="max-width: 170px"
          class="mr-3"
        />
        <v-btn color="primary" prepend-icon="mdi-printer" :disabled="!assets.length" @click="print">Print</v-btn>
      </v-card-title>
      <v-card-text>
        <p v-if="!assets.length" class="quiet text-body-2">No assets to label.</p>
        <div ref="sheet" class="label-grid">
          <div v-for="asset in assets" :key="asset.id || asset.asset_id" class="label-cell">
            <BarcodeLabel :value="asset.barcode_value || asset.asset_id" :caption="asset.description" :format="format" />
          </div>
        </div>
      </v-card-text>
      <v-card-actions>
        <span class="quiet text-caption px-2">{{ assets.length }} label(s)</span>
        <v-spacer />
        <v-btn variant="text" @click="$emit('update:modelValue', false)">Close</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script>
import BarcodeLabel from './BarcodeLabel.vue';

const PRINT_CSS = `
  @page { margin: 12mm; }
  body { font-family: Arial, Helvetica, sans-serif; margin: 0; }
  .label-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10mm 8mm; }
  .label-cell { border: 1px solid #ddd; border-radius: 6px; padding: 8px; text-align: center; page-break-inside: avoid; }
  .barcode-svg { width: 100%; height: 46px; }
  .barcode-id { font-weight: 700; font-size: 12px; margin-top: 4px; letter-spacing: 0.04em; }
  .barcode-caption { font-size: 10px; color: #555; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
`;

export default {
  components: { BarcodeLabel },
  props: {
    assets: { type: Array, default: () => [] },
    modelValue: { type: Boolean, default: false }
  },
  emits: ['update:modelValue'],
  data() {
    return {
      format: 'CODE128',
      formatItems: ['CODE128', 'CODE39']
    };
  },
  methods: {
    print() {
      const sheet = this.$refs.sheet;
      if (!sheet) return;
      const win = window.open('', '_blank', 'width=960,height=720');
      if (!win) return;
      win.document.write(
        `<html><head><title>Asset labels</title><style>${PRINT_CSS}</style></head>` +
        `<body><div class="label-grid">${sheet.innerHTML}</div></body></html>`
      );
      win.document.close();
      win.focus();
      setTimeout(() => {
        win.print();
        win.close();
      }, 350);
    }
  }
};
</script>
