<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'

const open = useOpenShipmentsModal()
const param = useOpenShipmentsModalParam()

const records = ref([])
const loading = ref(false)
const errorMsg = ref('')
const picklistModal = usePicklistModal()
const picklistModalParam = usePicklistModalParam()

const title = computed(() => {
  if (param.value?.org) return `Zu kommissionieren · ${param.value.org}`
  return 'Zu kommissionieren · Alle Organisationen'
})

const close = () => { open.value = false }

const fetchRecords = async () => {
  loading.value = true
  errorMsg.value = ''
  records.value = []
  try {
    const qs = param.value?.org ? `?org=${encodeURIComponent(param.value.org)}` : ''
    const res = await $fetch(`/api/inouts/open-to-commission-list${qs}`, {
      headers: useRequestHeaders(['cookie'])
    })
    records.value = res?.records || []
  } catch (e) {
    errorMsg.value = e?.message || 'Fehler beim Laden'
  } finally {
    loading.value = false
  }
}

watch(open, (val) => {
  if (val) fetchRecords()
})

const onKey = (e) => {
  if (e.key === 'Escape' && open.value) close()
}
onMounted(() => window.addEventListener('keydown', onKey))
onUnmounted(() => window.removeEventListener('keydown', onKey))

// Hand off to the picklist generator modal (sort + printer options, preview,
// download / server print). We already have the shipment list loaded, so pass the
// document numbers straight through to avoid a refetch.
const openPicklist = () => {
  const docNos = records.value.map(r => r.documentNo).filter(Boolean)
  if (!docNos.length) return
  picklistModalParam.value = {
    org: param.value?.org || null,
    docNos,
    title: param.value?.org ? `Pickliste – ${param.value.org}` : 'Pickliste – Zu kommissionieren',
  }
  picklistModal.value = true
}

const formatDate = (d) => {
  if (!d) return '—'
  const dt = new Date(d)
  if (Number.isNaN(dt.getTime())) return '—'
  return dt.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' })
}
</script>

<template>
  <Teleport to="body">
    <div v-if="open" class="ostm-overlay" @click.self="close">
      <div class="ostm-container" @click.stop>
        <header class="ostm-header">
          <div class="ostm-header__title">
            <span class="ostm-header__icon"><i class="ti ti-package"></i></span>
            <h3>{{ title }}</h3>
          </div>
          <button type="button" class="ostm-close" @click="close" title="Schließen">
            <i class="ti ti-x"></i>
          </button>
        </header>

        <div class="ostm-body">
          <div v-if="loading" class="ostm-state"><i class="ti ti-loader-2 ostm-spin"></i> Lade…</div>
          <div v-else-if="errorMsg" class="ostm-state ostm-state--error">{{ errorMsg }}</div>
          <div v-else-if="!records.length" class="ostm-state">Keine offenen Sendungen.</div>
          <div v-else class="ostm-table-wrap">
            <table class="ostm-table">
              <thead>
                <tr>
                  <th>Belegnr.</th>
                  <th>Datum</th>
                  <th>Status</th>
                  <th>Organisation</th>
                  <th>Lager</th>
                  <th>Kunde</th>
                  <th>Auftrag</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="r in records" :key="r.id">
                  <td>
                    <a :href="`/sales/shipments/${r.id}/edit`" target="_blank" rel="noopener noreferrer" class="ostm-link">
                      {{ r.documentNo || '—' }}
                    </a>
                  </td>
                  <td>{{ formatDate(r.movementDate) }}</td>
                  <td><span class="ostm-status">{{ r.docStatus || '—' }}</span></td>
                  <td class="ostm-truncate">{{ r.orgName }}</td>
                  <td class="ostm-truncate">{{ r.warehouseName || '—' }}</td>
                  <td class="ostm-truncate">{{ r.partnerName || '—' }}</td>
                  <td>
                    <a v-if="r.orderId" :href="`/sales/orders/${r.orderId}/edit`" target="_blank" rel="noopener noreferrer" class="ostm-link">
                      {{ r.orderNo || '#' + r.orderId }}
                    </a>
                    <span v-else>—</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <footer class="ostm-footer">
          <span class="ostm-count" v-if="!loading && !errorMsg">{{ records.length }} {{ records.length === 1 ? 'Sendung' : 'Sendungen' }}</span>
          <div class="ostm-footer__actions">
            <button
              type="button"
              class="ostm-icon-btn"
              :disabled="!records.length"
              @click="openPicklist"
              title="Pickliste erstellen / drucken (Backup)"
              aria-label="Pickliste erstellen"
            >
              <i class="ti ti-printer"></i>
            </button>
            <button type="button" class="ostm-btn" @click="close">Schließen</button>
          </div>
        </footer>
      </div>
    </div>
  </Teleport>
</template>

<style>
/* Unscoped — Teleport target is <body>; scoped styles wouldn't apply. */
.ostm-overlay {
  position: fixed; inset: 0;
  background: rgba(15, 23, 42, 0.55);
  display: flex; align-items: center; justify-content: center;
  z-index: 7000; padding: 1.5rem;
}
.ostm-container {
  width: 100%; max-width: 1100px; max-height: 88vh;
  background: var(--theme-bg-primary, #fff);
  color: var(--theme-text-primary, #0f172a);
  border-radius: 10px; overflow: hidden;
  display: flex; flex-direction: column;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25);
}
.ostm-header {
  display: flex; align-items: center; justify-content: space-between;
  padding: 0.875rem 1rem;
  background: linear-gradient(180deg, rgba(244, 63, 94, 0.10), transparent);
  border-bottom: 1px solid var(--theme-border, #e6e8ec);
}
.ostm-header__title { display: flex; align-items: center; gap: 0.625rem; }
.ostm-header__title h3 { margin: 0; font-size: 1rem; font-weight: 700; }
.ostm-header__icon {
  width: 32px; height: 32px;
  display: inline-flex; align-items: center; justify-content: center;
  background: #f43f5e; color: #fff; border-radius: 8px;
}
.ostm-close {
  background: transparent; border: 0; cursor: pointer;
  width: 32px; height: 32px; border-radius: 6px;
  color: var(--theme-text-secondary, #64748b);
  display: inline-flex; align-items: center; justify-content: center;
  font-size: 1.1rem;
}
.ostm-close:hover { background: var(--theme-bg-secondary, #f1f5f9); }
.ostm-body { flex: 1; overflow: auto; padding: 0.75rem 1rem 1rem; }
.ostm-state {
  display: flex; align-items: center; justify-content: center; gap: 0.5rem;
  padding: 2rem 1rem; color: var(--theme-text-secondary, #64748b);
}
.ostm-state--error { color: #b91c1c; }
.ostm-spin { animation: ostm-spin 0.9s linear infinite; }
@keyframes ostm-spin { to { transform: rotate(360deg); } }
.ostm-table-wrap { width: 100%; overflow: auto; }
.ostm-table { width: 100%; border-collapse: collapse; font-size: 0.8125rem; }
.ostm-table th, .ostm-table td {
  text-align: left; padding: 0.5rem 0.625rem;
  border-bottom: 1px solid var(--theme-border, #eef0f3);
  white-space: nowrap;
}
.ostm-table th {
  font-weight: 600; color: var(--theme-text-secondary, #475569);
  background: var(--theme-bg-secondary, #fafbfc);
  position: sticky; top: 0; z-index: 1;
}
.ostm-truncate { max-width: 220px; overflow: hidden; text-overflow: ellipsis; }
.ostm-link { color: var(--accent, #3b82f6); text-decoration: none; font-weight: 600; }
.ostm-link:hover { text-decoration: underline; }
.ostm-status {
  display: inline-block; padding: 0.1rem 0.45rem;
  border-radius: 999px; font-size: 0.7rem; font-weight: 700;
  background: rgba(244, 63, 94, 0.12); color: #b91c1c;
}
.ostm-footer {
  display: flex; align-items: center; justify-content: space-between;
  padding: 0.625rem 1rem;
  border-top: 1px solid var(--theme-border, #eef0f3);
  background: var(--theme-bg-secondary, #fafbfc);
}
.ostm-count { font-size: 0.8125rem; color: var(--theme-text-secondary, #64748b); }
.ostm-footer__actions { display: inline-flex; align-items: center; gap: 0.5rem; }
.ostm-btn {
  background: #f43f5e; color: #fff; border: 0; cursor: pointer;
  padding: 0.45rem 0.9rem; border-radius: 6px; font-weight: 600;
  display: inline-flex; align-items: center; gap: 0.35rem;
}
.ostm-btn:hover { background: #e11d48; }
.ostm-btn:disabled { opacity: 0.5; cursor: not-allowed; }
.ostm-btn i { font-size: 1rem; }
.ostm-icon-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 34px;
  height: 34px;
  background: transparent;
  color: #f43f5e;
  border: 1px solid #f43f5e;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.15s ease;
}
.ostm-icon-btn:hover { background: rgba(244, 63, 94, 0.08); }
.ostm-icon-btn:disabled { opacity: 0.5; cursor: not-allowed; }
.ostm-icon-btn i { font-size: 1.05rem; }
[data-mode="dark"] .ostm-container {
  background: #0f172a; color: #e2e8f0;
}
[data-mode="dark"] .ostm-table th { background: rgba(255,255,255,0.04); color: #cbd5e1; }
[data-mode="dark"] .ostm-table th,
[data-mode="dark"] .ostm-table td { border-color: rgba(255,255,255,0.08); }
[data-mode="dark"] .ostm-footer { background: rgba(255,255,255,0.03); border-color: rgba(255,255,255,0.08); }
</style>
