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

const open = useOpenOrdersModal()
const param = useOpenOrdersModalParam()

const records = ref([])
const loading = ref(false)
const errorMsg = ref('')

const title = computed(() => {
  const base = 'Offene Aufträge'
  const orgPart = param.value?.org ? ` · ${param.value.org}` : ' · Alle Organisationen'
  const statusPart =
    param.value?.status === 'fillable'   ? ' · Erfüllbar' :
    param.value?.status === 'unfillable' ? ' · Nicht erfüllbar' : ''
  return `${base}${orgPart}${statusPart}`
})

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

const fetchRecords = async () => {
  loading.value = true
  errorMsg.value = ''
  records.value = []
  try {
    const params = {}
    if (param.value?.org) params.org = param.value.org
    if (param.value?.status && param.value.status !== 'all') params.status = param.value.status
    const res = await $fetch('/api/orders/openso-list', {
      headers: useRequestHeaders(['cookie']),
      params
    })
    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))

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' })
}

const formatCurrency = (val) => {
  const n = Number(val ?? 0)
  return new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(n)
}

const summary = computed(() => {
  const total = records.value.length
  const unfillable = records.value.filter(r => r.isUnfulfillable).length
  return { total, fillable: total - unfillable, unfillable }
})
</script>

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

        <div class="oomd-body">
          <div v-if="loading" class="oomd-state"><i class="ti ti-loader-2 oomd-spin"></i> Lade…</div>
          <div v-else-if="errorMsg" class="oomd-state oomd-state--error">{{ errorMsg }}</div>
          <div v-else-if="!records.length" class="oomd-state">Keine offenen Aufträge.</div>
          <div v-else class="oomd-table-wrap">
            <table class="oomd-table">
              <thead>
                <tr>
                  <th>Belegnr.</th>
                  <th>Datum</th>
                  <th>Zugesagt</th>
                  <th>Organisation</th>
                  <th>Kunde</th>
                  <th class="ta-right">Summe</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="r in records" :key="r.id">
                  <td>
                    <a :href="`/sales/orders/${r.id}/edit`" target="_blank" rel="noopener noreferrer" class="oomd-link">
                      {{ r.documentNo || '—' }}
                    </a>
                  </td>
                  <td>{{ formatDate(r.dateOrdered) }}</td>
                  <td>{{ formatDate(r.datePromised) }}</td>
                  <td class="oomd-truncate">{{ r.orgName }}</td>
                  <td class="oomd-truncate">{{ r.partnerName || '—' }}</td>
                  <td class="ta-right">{{ formatCurrency(r.grandTotal) }}</td>
                  <td>
                    <span :class="['oomd-badge', r.isUnfulfillable ? 'oomd-badge--bad' : 'oomd-badge--ok']">
                      <i :class="r.isUnfulfillable ? 'ti ti-alert-triangle-filled' : 'ti ti-circle-check-filled'"></i>
                      {{ r.isUnfulfillable ? 'Nicht erfüllbar' : 'Erfüllbar' }}
                    </span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <footer class="oomd-footer">
          <span v-if="!loading && !errorMsg" class="oomd-count">
            {{ summary.total }} {{ summary.total === 1 ? 'Auftrag' : 'Aufträge' }}
            <template v-if="summary.total > 0">
              · <span class="oomd-pill oomd-pill--ok">{{ summary.fillable }} erfüllbar</span>
              · <span class="oomd-pill oomd-pill--bad">{{ summary.unfillable }} nicht erfüllbar</span>
            </template>
          </span>
          <button type="button" class="oomd-btn" @click="close">Schließen</button>
        </footer>
      </div>
    </div>
  </Teleport>
</template>

<style>
/* Unscoped — Teleport target is <body>; scoped styles wouldn't apply. */
.oomd-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;
}
.oomd-container {
  width: 100%; max-width: 1200px; 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);
}
.oomd-header {
  display: flex; align-items: center; justify-content: space-between;
  padding: 0.875rem 1rem;
  background: linear-gradient(180deg, rgba(99, 102, 241, 0.10), transparent);
  border-bottom: 1px solid var(--theme-border, #e6e8ec);
}
.oomd-header__title { display: flex; align-items: center; gap: 0.625rem; }
.oomd-header__title h3 { margin: 0; font-size: 1rem; font-weight: 700; }
.oomd-header__icon {
  width: 32px; height: 32px;
  display: inline-flex; align-items: center; justify-content: center;
  background: #6366f1; color: #fff; border-radius: 8px;
}
.oomd-close {
  background: transparent; border: 0; cursor: pointer;
  width: 32px; height: 32px; border-radius: 6px;
  color: var(--theme-text-secondary, #64748b);
}
.oomd-close:hover { background: var(--theme-bg-secondary, #f1f5f9); }
.oomd-body { flex: 1; overflow: auto; padding: 0.75rem 1rem; }
.oomd-state { padding: 2rem 1rem; text-align: center; color: var(--theme-text-secondary, #64748b); }
.oomd-state--error { color: #b91c1c; }
.oomd-spin { display: inline-block; animation: oomd-spin 0.8s linear infinite; }
@keyframes oomd-spin { to { transform: rotate(360deg); } }
.oomd-table-wrap { overflow: auto; border-radius: 8px; border: 1px solid var(--theme-border, #e6e8ec); }
.oomd-table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }
.oomd-table th, .oomd-table td {
  padding: 0.5rem 0.75rem;
  border-bottom: 1px solid var(--theme-border, #eef0f3);
  text-align: left;
  white-space: nowrap;
}
.oomd-table th { background: var(--theme-bg-secondary, #f8fafc); font-weight: 700; color: var(--theme-text-secondary, #475569); }
.oomd-table tr:last-child td { border-bottom: 0; }
.oomd-table .ta-right { text-align: right; }
.oomd-truncate { max-width: 220px; overflow: hidden; text-overflow: ellipsis; }
.oomd-link { color: #2563eb; text-decoration: none; font-weight: 600; }
.oomd-link:hover { text-decoration: underline; }
.oomd-badge {
  display: inline-flex; align-items: center; gap: 0.25rem;
  padding: 0.125rem 0.5rem; border-radius: 999px;
  font-size: 0.7rem; font-weight: 700;
}
.oomd-badge--ok  { background: rgba(34,197,94,0.12);  color: #16a34a; }
.oomd-badge--bad { background: rgba(239,68,68,0.12);  color: #dc2626; }
.oomd-footer {
  display: flex; align-items: center; justify-content: space-between;
  padding: 0.625rem 1rem;
  background: var(--theme-bg-secondary, #f8fafc);
  border-top: 1px solid var(--theme-border, #e6e8ec);
  gap: 0.75rem; flex-wrap: wrap;
}
.oomd-count { font-size: 0.8rem; color: var(--theme-text-secondary, #475569); }
.oomd-pill {
  display: inline-flex; align-items: center;
  padding: 0.0625rem 0.375rem; border-radius: 999px;
  font-size: 0.7rem; font-weight: 700;
}
.oomd-pill--ok  { background: rgba(34,197,94,0.12);  color: #16a34a; }
.oomd-pill--bad { background: rgba(239,68,68,0.12);  color: #dc2626; }
.oomd-btn {
  padding: 0.375rem 0.875rem;
  background: var(--theme-bg-primary, #fff);
  border: 1px solid var(--theme-border, #d1d5db);
  color: var(--theme-text-primary, #0f172a);
  border-radius: 6px;
  font-size: 0.85rem; font-weight: 600;
  cursor: pointer;
}
.oomd-btn:hover { background: var(--theme-bg-secondary, #f1f5f9); }

/* Dark mode */
[data-mode="dark"] .oomd-table th { background: #1f2937; color: #cbd5e1; }
[data-mode="dark"] .oomd-table td { border-color: #2b3441; }
[data-mode="dark"] .oomd-link { color: #60a5fa; }
[data-mode="dark"] .oomd-footer { background: #1a212c; }
</style>
