<template>
  <div class="printer-installer">
    <div class="map-pane">
      <div class="map-header">
        <router-link to="/printers" class="back-link">&larr; Printers</router-link>
        <h1>Printer Installer</h1>
        <span class="hint">Click printers on the map to select, then install.</span>
      </div>
      <div ref="mapContainer" class="map-canvas"></div>
    </div>

    <aside class="select-pane">
      <h2>Selected <span class="count">{{ selectedList.length }}</span></h2>

      <div v-if="!selectedList.length" class="empty">
        No printers selected yet. Click a marker on the map.
      </div>
      <ul v-else class="selected-list">
        <li v-for="p in selectedList" :key="p.printerid">
          <span class="pname">{{ printerLabel(p) }}</span>
          <span class="ploc" v-if="p.locationname">{{ p.locationname }}</span>
          <button class="remove" title="Remove" @click="toggle(p.printerid)">&times;</button>
        </li>
      </ul>

      <button class="btn-install" :disabled="!selectedList.length" @click="downloadBatch">
        Install {{ selectedList.length }} printer(s)
      </button>
      <button v-if="selectedList.length" class="btn-clear" @click="clearSelection">
        Clear selection
      </button>

      <p class="note">
        Downloads a .bat that installs the selected printers (universal
        installer for HP/Xerox, the printer's own installer otherwise). Run it on
        the target PC.
      </p>
    </aside>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'
import { loadMapConfig, blueprintUrlFor, dimensionsFor, state as mapConfig } from '@/composables/mapConfig'
import { printersApi } from '@/api'
import { withBase } from '@/utils/basePath'
import { currentTheme } from '@/stores/theme'

const mapContainer = ref(null)
const printers = ref([])
const selected = ref({})   // printerid -> true

let map = null
let imageOverlay = null
let markers = {}           // printerid -> circleMarker
// The level being shown. The installer map runs before anyone logs in, which is
// why /api/maplevels is public - without it there is no blueprint to draw.
let MAP_WIDTH = 0
let MAP_HEIGHT = 0

const SELECTED_COLOR = '#e53935'
const NORMAL_COLOR = '#4CAF50'

const selectedList = computed(() =>
  printers.value.filter(p => selected.value[p.printerid]))

function printerLabel(p) {
  return p.windowsname || p.sharename || p.name || p.machinenumber || ('#' + p.printerid)
}

function markerStyle(isSelected) {
  return {
    radius: isSelected ? 9 : 6,
    color: '#222',
    weight: 1,
    fillColor: isSelected ? SELECTED_COLOR : NORMAL_COLOR,
    fillOpacity: 0.95,
  }
}

function toggle(printerid) {
  if (selected.value[printerid]) {
    delete selected.value[printerid]
  } else {
    selected.value[printerid] = true
  }
  const marker = markers[printerid]
  if (marker) marker.setStyle(markerStyle(!!selected.value[printerid]))
}

function clearSelection() {
  for (const id of Object.keys(selected.value)) {
    if (markers[id]) markers[id].setStyle(markerStyle(false))
  }
  selected.value = {}
}

function downloadBatch() {
  const ids = selectedList.value.map(p => p.printerid).join(',')
  if (!ids) return
  // install-batch is optional-auth, so a plain anchor download works (an anchor
  // cannot carry the JWT bearer header). withBase keeps it under the mount.
  const url = withBase('/api/printers/install-batch?printerids=' + encodeURIComponent(ids))
  const link = document.createElement('a')
  link.href = url
  link.click()
}

function renderMarkers() {
  for (const p of printers.value) {
    if (p.mapx == null || p.mapy == null) continue
    const leafletY = MAP_HEIGHT - p.mapy
    const leafletX = p.mapx
    const marker = L.circleMarker([leafletY, leafletX], markerStyle(false))
    marker.bindTooltip(printerLabel(p), { direction: 'top' })
    marker.on('click', () => toggle(p.printerid))
    marker.addTo(map)
    markers[p.printerid] = marker
  }
}

watch(currentTheme, (theme) => {
  if (imageOverlay) imageOverlay.setUrl(blueprintUrlFor(theme, mapConfig.currentlevelid))
})

onMounted(async () => {
  await loadMapConfig()
  MAP_WIDTH = dimensionsFor(mapConfig.currentlevelid).width
  MAP_HEIGHT = dimensionsFor(mapConfig.currentlevelid).height

  try {
    const response = await printersApi.installList()
    printers.value = response.data.data || []
  } catch (e) {
    printers.value = []
  }

  map = L.map(mapContainer.value, {
    crs: L.CRS.Simple,
    minZoom: -4,
    maxZoom: 2,
    attributionControl: false,
  })
  const bounds = [[0, 0], [MAP_HEIGHT, MAP_WIDTH]]
  imageOverlay = L.imageOverlay(blueprintUrlFor(currentTheme.value, mapConfig.currentlevelid), bounds).addTo(map)
  map.setView([MAP_HEIGHT / 2, MAP_WIDTH / 2], -2)
  map.setMaxBounds(bounds)
  renderMarkers()
})

onUnmounted(() => {
  if (map) map.remove()
})
</script>

<style scoped>
.printer-installer {
  display: flex;
  height: 100vh;
  width: 100vw;
  background: var(--bg);
}
.map-pane { flex: 1; display: flex; flex-direction: column; min-width: 0; }
.map-header {
  display: flex;
  align-items: baseline;
  gap: 1rem;
  padding: 0.75rem 1rem;
  border-bottom: 1px solid var(--border);
  background: var(--bg-card);
}
.map-header h1 { font-size: 1.2rem; margin: 0; color: var(--text); }
.back-link { color: var(--link); text-decoration: none; font-size: 0.9rem; }
.hint { color: var(--text-light); font-size: 0.85rem; margin-left: auto; }
.map-canvas { flex: 1; background: var(--bg); }

.select-pane {
  width: 320px;
  flex-shrink: 0;
  border-left: 1px solid var(--border);
  background: var(--bg-card);
  padding: 1rem;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}
.select-pane h2 { font-size: 1rem; margin: 0 0 0.75rem; color: var(--text); }
.count {
  background: var(--primary);
  color: #fff;
  border-radius: 10px;
  padding: 0.05rem 0.5rem;
  font-size: 0.85rem;
  margin-left: 0.25rem;
}
.empty { color: var(--text-light); font-size: 0.9rem; padding: 1rem 0; }
.selected-list { list-style: none; margin: 0 0 1rem; padding: 0; }
.selected-list li {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  padding: 0.4rem 0;
  border-bottom: 1px solid var(--border);
}
.pname { color: var(--text); font-weight: 600; font-size: 0.85rem; }
.ploc { color: var(--text-light); font-size: 0.75rem; }
.remove {
  margin-left: auto;
  background: none;
  border: none;
  color: var(--danger);
  font-size: 1.1rem;
  cursor: pointer;
  line-height: 1;
}
.btn-install {
  width: 100%;
  padding: 0.6rem;
  background: var(--primary);
  color: #fff;
  border: none;
  border-radius: 4px;
  font-weight: 600;
  cursor: pointer;
}
.btn-install:disabled { opacity: 0.5; cursor: not-allowed; }
.btn-clear {
  width: 100%;
  margin-top: 0.5rem;
  padding: 0.4rem;
  background: transparent;
  color: var(--text-light);
  border: 1px solid var(--border);
  border-radius: 4px;
  cursor: pointer;
}
.note { color: var(--text-light); font-size: 0.75rem; margin-top: 1rem; line-height: 1.4; }
</style>
