<script setup lang="ts">
/**
 * Allocation confirm dialog — opens when an inbound truck is dropped onto an
 * outbound truck. Lines are pre-matched by product (match-proposal endpoint)
 * with quantities pre-filled to the maximum coverable amount; the user adjusts
 * and confirms. Confirm bulk-upserts CUST_CrossDockAlloc rows.
 */
const board = inject('cdBoard') as ReturnType<typeof useCrossdockBoard>

const dialog = computed(() => board.allocDialog.value)

const poDoc = computed(() => board.inboundById.value[dialog.value.poOrderId]?.documentNo ?? `#${dialog.value.poOrderId}`)
const soDoc = computed(() => board.outboundById.value[dialog.value.soOrderId]?.documentNo ?? `#${dialog.value.soOrderId}`)
const poPartner = computed(() => board.inboundById.value[dialog.value.poOrderId]?.partnerName ?? '')
const soPartner = computed(() => board.outboundById.value[dialog.value.soOrderId]?.partnerName ?? '')

const totalQty = computed(() => dialog.value.rows.reduce((s, r) => s + (Number(r.qty) || 0), 0))
const hasChanges = computed(() =>
  dialog.value.rows.some(r => (Number(r.qty) || 0) !== r.existingQty)
)

const clampQty = (row: any) => {
  const v = Number(row.qty)
  if (!Number.isFinite(v) || v < 0) row.qty = 0
  else if (v > row.maxQty) row.qty = row.maxQty
}

const fillMax = () => { for (const r of dialog.value.rows) r.qty = r.maxQty }
const clearAll = () => { for (const r of dialog.value.rows) r.qty = 0 }

const close = () => { board.allocDialog.value.open = false }
</script>

<template>
  <div class="modal" :class="{ 'is-active': dialog.open }">
    <div class="modal-background" @click="close"></div>
    <div class="modal-card cdam">
      <header class="modal-card-head cdam__head">
        <div class="cdam__title">
          <span class="ti ti-transfer cdam__titleIcon"></span>
          <div>
            <p class="modal-card-title cdam__titleText">Cross-Dock Zuordnung</p>
            <p class="cdam__subtitle">
              <span class="cdam__doc cdam__doc--in"><span class="ti ti-truck-delivery"></span> {{ poDoc }} <small>{{ poPartner }}</small></span>
              <span class="ti ti-arrow-right cdam__arrow"></span>
              <span class="cdam__doc cdam__doc--out"><span class="ti ti-truck"></span> {{ soDoc }} <small>{{ soPartner }}</small></span>
            </p>
          </div>
        </div>
        <button class="delete" aria-label="close" @click="close"></button>
      </header>

      <section class="modal-card-body">
        <div v-if="dialog.loading" class="cdam__loading">
          <span class="ti ti-loader cdam__spin"></span> Positionen werden abgeglichen…
        </div>

        <template v-else>
          <div v-if="!dialog.rows.length" class="notification is-warning is-light">
            <span class="ti ti-mood-empty mr-1"></span>
            Keine übereinstimmenden Produkte zwischen Bestellung und Auftrag gefunden —
            eine Cross-Dock Zuordnung ist hier nicht möglich.
          </div>

          <template v-else>
            <div class="cdam__actions">
              <button type="button" class="button is-small" @click="fillMax">
                <span class="ti ti-arrow-bar-to-up mr-1"></span> Maximum zuordnen
              </button>
              <button type="button" class="button is-small" @click="clearAll">
                <span class="ti ti-eraser mr-1"></span> Alle auf 0
              </button>
            </div>

            <table class="table is-fullwidth is-narrow cdam__table">
              <thead>
                <tr>
                  <th>Produkt</th>
                  <th class="has-text-right">Offen (Eingang)</th>
                  <th class="has-text-right">Offen (Auftrag)</th>
                  <th class="has-text-right">Max</th>
                  <th class="has-text-right" style="width: 120px">Zuordnen</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="row in dialog.rows" :key="row.poOrderLineId + '-' + row.soOrderLineId">
                  <td>
                    <div class="cdam__prod">{{ row.productName }}</div>
                    <div class="cdam__sku">{{ row.sku }}</div>
                  </td>
                  <td class="has-text-right">
                    {{ row.poOpenQty }}
                    <span v-if="row.poAllocatedOther" class="cdam__other" :title="`davon ${row.poAllocatedOther} bereits anderweitig zugeordnet`">
                      (−{{ row.poAllocatedOther }})
                    </span>
                  </td>
                  <td class="has-text-right">
                    {{ row.soOpenQty }}
                    <span v-if="row.soAllocatedOther" class="cdam__other" :title="`davon ${row.soAllocatedOther} bereits anderweitig zugeordnet`">
                      (−{{ row.soAllocatedOther }})
                    </span>
                  </td>
                  <td class="has-text-right">{{ row.maxQty }}</td>
                  <td>
                    <input
                      v-model.number="row.qty"
                      class="input is-small has-text-right"
                      type="number"
                      min="0"
                      :max="row.maxQty"
                      step="1"
                      @change="clampQty(row)"
                    />
                  </td>
                </tr>
              </tbody>
              <tfoot>
                <tr>
                  <th colspan="4" class="has-text-right">Gesamt zugeordnet</th>
                  <th class="has-text-right">{{ totalQty }}</th>
                </tr>
              </tfoot>
            </table>
          </template>
        </template>
      </section>

      <footer class="modal-card-foot cdam__foot">
        <button type="button" class="button" @click="close">Abbrechen</button>
        <button
          type="button"
          class="button is-primary"
          :class="{ 'is-loading': dialog.saving }"
          :disabled="dialog.loading || !dialog.rows.length || !hasChanges"
          @click="board.saveAllocation()"
        >
          <span class="ti ti-link mr-1"></span> Zuordnung speichern
        </button>
      </footer>
    </div>
  </div>
</template>

<style scoped>
.cdam {
  width: min(860px, calc(100vw - 32px));
}
.cdam__head {
  align-items: flex-start;
}
.cdam__title {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}
.cdam__titleIcon {
  font-size: 1.6rem;
  margin-top: 2px;
}
.cdam__titleText {
  margin-bottom: 2px;
}
.cdam__subtitle {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 0.85rem;
  flex-wrap: wrap;
}
.cdam__doc {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 6px;
  color: #ffffff;
}
.cdam__doc small {
  font-weight: 400;
  opacity: 0.85;
}
.cdam__doc--in { background: linear-gradient(#42628c, #2c4661); }
.cdam__doc--out { background: linear-gradient(#6a5da8, #4a3f7d); }
.cdam__arrow { opacity: 0.6; }

.cdam__loading {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
  padding: 32px 0;
  color: var(--theme-text-secondary, #7a8194);
}
.cdam__spin {
  animation: cdamSpin 0.9s linear infinite;
}
@keyframes cdamSpin { to { transform: rotate(360deg); } }

.cdam__actions {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}
.cdam__prod {
  font-weight: 600;
}
.cdam__sku {
  font-size: 0.75rem;
  color: var(--theme-text-secondary, #7a8194);
}
.cdam__other {
  font-size: 0.72rem;
  color: #b47d19;
}
.cdam__foot {
  justify-content: flex-end;
}
</style>
