<script setup>
import { date } from 'alga-js'

const props = defineProps({
  hiddenShipmentId: {
    type: Number,
    default: null
  }
})

const emit = defineEmits(['select'])

const {
  openShipments,
  isLoading,
  error,
  lastFetched,
  fetchOpenShipments,
  refresh
} = useOpenShipments()

// Fetch on mount (non-blocking)
onMounted(() => {
  fetchOpenShipments()
})

// Auto-refresh every 2 minutes
let refreshInterval = null
onMounted(() => {
  refreshInterval = setInterval(() => {
    fetchOpenShipments()
  }, 2 * 60 * 1000)
})

onUnmounted(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})

const selectShipment = (shipment) => {
  emit('select', shipment.DocumentNo, shipment.id)
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const d = new Date(dateStr)
  return d.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' })
}

// Sorting state
const sortBy = ref('date') // 'org', 'qty', 'date'
const sortAsc = ref(false) // false = descending (newest first by default)

const toggleSort = (field) => {
  if (sortBy.value === field) {
    // Same field - toggle direction
    sortAsc.value = !sortAsc.value
  } else {
    // New field - set default direction
    sortBy.value = field
    sortAsc.value = field === 'org' // org ascending by default, others descending
  }
}

// Filter out the currently loaded shipment
const filteredShipments = computed(() => {
  if (!props.hiddenShipmentId) {
    return openShipments.value
  }
  return openShipments.value.filter(s => s.id !== props.hiddenShipmentId)
})

// Sort the filtered shipments
const visibleShipments = computed(() => {
  const shipments = [...filteredShipments.value]

  shipments.sort((a, b) => {
    let comparison = 0

    if (sortBy.value === 'org') {
      const orgA = (a.AD_Org_ID?.Name || a.AD_Org_ID?.identifier || '').toLowerCase()
      const orgB = (b.AD_Org_ID?.Name || b.AD_Org_ID?.identifier || '').toLowerCase()
      comparison = orgA.localeCompare(orgB)
    } else if (sortBy.value === 'qty') {
      comparison = (a.totalQty || 0) - (b.totalQty || 0)
    } else if (sortBy.value === 'date') {
      const dateA = new Date(a.MovementDate || 0).getTime()
      const dateB = new Date(b.MovementDate || 0).getTime()
      comparison = dateA - dateB
    }

    return sortAsc.value ? comparison : -comparison
  })

  return shipments
})

// Group shipments by organization (using visible shipments)
const groupedShipments = computed(() => {
  const groups = {}
  for (const shipment of visibleShipments.value) {
    const orgName = shipment.AD_Org_ID?.Name || shipment.AD_Org_ID?.identifier || 'Unknown'
    if (!groups[orgName]) {
      groups[orgName] = []
    }
    groups[orgName].push(shipment)
  }
  return groups
})

const totalOpenCount = computed(() => visibleShipments.value.length)

// Expose refresh and openShipments for parent to call after commission and search
defineExpose({ refresh, openShipments })
</script>

<template>
  <div class="openShipmentsPanel">
    <div class="openShipmentsHeader">
      <div class="headerTitle">
        <i class="ti ti-package"></i>
        <span>Open Shipments</span>
      </div>
      <div class="headerBadge" :class="{ 'has-items': totalOpenCount > 0 }">
        {{ totalOpenCount }}
      </div>
    </div>

    <div class="openShipmentsActions">
      <button
        type="button"
        class="refreshBtn"
        @click="refresh"
        :disabled="isLoading"
        :class="{ 'is-loading': isLoading }"
      >
        <i class="ti ti-refresh" :class="{ 'spin': isLoading }"></i>
        <span>Refresh</span>
      </button>
      <div v-if="lastFetched" class="lastUpdated">
        {{ lastFetched.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' }) }}
      </div>
    </div>

    <div class="sortButtons">
      <button
        type="button"
        class="sortBtn"
        :class="{ active: sortBy === 'org' }"
        @click="toggleSort('org')"
        title="Sort by Organization"
      >
        <i class="ti ti-building"></i>
        <i v-if="sortBy === 'org'" class="sortArrow" :class="[sortAsc ? 'ti ti-arrow-up' : 'ti ti-arrow-down']"></i>
      </button>
      <button
        type="button"
        class="sortBtn"
        :class="{ active: sortBy === 'qty' }"
        @click="toggleSort('qty')"
        title="Sort by Quantity"
      >
        <i class="ti ti-stack-2"></i>
        <i v-if="sortBy === 'qty'" class="sortArrow" :class="[sortAsc ? 'ti ti-arrow-up' : 'ti ti-arrow-down']"></i>
      </button>
      <button
        type="button"
        class="sortBtn"
        :class="{ active: sortBy === 'date' }"
        @click="toggleSort('date')"
        title="Sort by Date"
      >
        <i class="ti ti-calendar"></i>
        <i v-if="sortBy === 'date'" class="sortArrow" :class="[sortAsc ? 'ti ti-arrow-up' : 'ti ti-arrow-down']"></i>
      </button>
    </div>

    <div class="openShipmentsBody">
      <!-- Loading state -->
      <div v-if="isLoading && visibleShipments.length === 0" class="loadingState">
        <i class="ti ti-loader spin"></i>
        <span>Loading shipments...</span>
      </div>

      <!-- Error state -->
      <div v-else-if="error" class="errorState">
        <i class="ti ti-alert-circle"></i>
        <span>{{ error }}</span>
        <button type="button" class="retryBtn" @click="refresh">Retry</button>
      </div>

      <!-- Empty state -->
      <div v-else-if="visibleShipments.length === 0" class="emptyState">
        <i class="ti ti-package-off"></i>
        <span>No open shipments</span>
      </div>

      <!-- Shipments list grouped by organization -->
      <div v-else class="shipmentGroups">
        <div v-for="(shipments, orgName) in groupedShipments" :key="orgName" class="shipmentGroup">
          <div class="groupHeader">
            <i class="ti ti-building"></i>
            <span class="orgName">{{ orgName }}</span>
            <span class="groupCount">{{ shipments.length }}</span>
          </div>
          <div class="groupItems">
            <div
              v-for="shipment in shipments"
              :key="shipment.id"
              class="shipmentItem"
              @click="selectShipment(shipment)"
            >
              <div class="shipmentMain">
                <div class="shipmentDocNo">
                  <i class="ti ti-file-text"></i>
                  {{ shipment.DocumentNo }}
                </div>
                <div class="shipmentQty">
                  <span class="qtyValue">{{ shipment.totalQty || 0 }}</span>
                  <span class="qtyLabel">items</span>
                </div>
              </div>
              <div class="shipmentDetails">
                <div class="shipmentCustomer" :title="shipment.C_BPartner_Location_ID?.Name || shipment.C_BPartner_Location_ID?.identifier">
                  <i class="ti ti-user"></i>
                  <span>{{ shipment.C_BPartner_Location_ID?.Name || shipment.C_BPartner_Location_ID?.identifier || shipment.C_BPartner_ID?.identifier || '-' }}</span>
                </div>
                <div class="shipmentDate">
                  <i class="ti ti-calendar"></i>
                  <span>{{ formatDate(shipment.MovementDate) }}</span>
                </div>
              </div>
              <div v-if="shipment.M_Shipper_ID" class="shipmentShipper">
                <i class="ti ti-truck"></i>
                <span>{{ shipment.M_Shipper_ID.identifier }}</span>
              </div>
              <div v-if="shipment.POReference" class="shipmentRef">
                <span class="refLabel">Ref:</span>
                <span class="refValue">{{ shipment.POReference }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.openShipmentsPanel {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #fff;
  border-right: 1px solid #e0e0e0;
}

.openShipmentsHeader {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.headerTitle {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-weight: 600;
  font-size: 1rem;
}

.headerTitle i {
  font-size: 1.25rem;
}

.headerBadge {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  padding: 0.25rem 0.75rem;
  border-radius: 20px;
  font-weight: 700;
  font-size: 0.9rem;
  min-width: 2rem;
  text-align: center;
}

.headerBadge.has-items {
  background: #f14668;
}

.openShipmentsActions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0.5rem 0.75rem;
  background: #f8f8f8;
  border-bottom: 1px solid #e0e0e0;
}

.refreshBtn {
  display: flex;
  align-items: center;
  gap: 0.35rem;
  padding: 0.35rem 0.75rem;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.8rem;
  cursor: pointer;
  transition: all 0.15s ease;
}

.refreshBtn:hover:not(:disabled) {
  background: #f0f0f0;
  border-color: #ccc;
}

.refreshBtn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.refreshBtn i.spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.lastUpdated {
  font-size: 0.75rem;
  color: #888;
}

.sortButtons {
  display: flex;
  align-items: center;
  justify-content: stretch;
  gap: 0.35rem;
  padding: 0.5rem;
  background: #f0f0f0;
  border-bottom: 1px solid #e0e0e0;
}

.sortBtn {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
  gap: 0.25rem;
  padding: 0.4rem 0.6rem;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.85rem;
  cursor: pointer;
  transition: all 0.15s ease;
  color: #666;
}

.sortBtn:hover {
  background: #f8f8f8;
  border-color: #ccc;
  color: #333;
}

.sortBtn.active {
  background: #667eea;
  border-color: #667eea;
  color: white;
}

.sortBtn .sortArrow {
  font-size: 0.7rem;
  margin-left: 0.1rem;
}

.openShipmentsBody {
  flex: 1;
  overflow-y: auto;
  padding: 0.5rem;
}

.loadingState,
.errorState,
.emptyState {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 2rem 1rem;
  color: #888;
  text-align: center;
  gap: 0.5rem;
}

.loadingState i,
.emptyState i {
  font-size: 2rem;
  margin-bottom: 0.5rem;
}

.errorState {
  color: #f14668;
}

.errorState i {
  font-size: 2rem;
}

.retryBtn {
  margin-top: 0.5rem;
  padding: 0.35rem 1rem;
  background: #f14668;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.85rem;
}

.retryBtn:hover {
  background: #e8425e;
}

.shipmentGroups {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.shipmentGroup {
  background: #fafafa;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #eee;
}

.groupHeader {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  background: linear-gradient(135deg, #e8e8e8 0%, #f0f0f0 100%);
  font-size: 0.85rem;
  font-weight: 600;
  color: #555;
  border-bottom: 1px solid #ddd;
}

.groupHeader i {
  color: #888;
}

.orgName {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.groupCount {
  background: #667eea;
  color: white;
  padding: 0.15rem 0.5rem;
  border-radius: 10px;
  font-size: 0.75rem;
}

.groupItems {
  display: flex;
  flex-direction: column;
}

.shipmentItem {
  padding: 0.6rem 0.75rem;
  cursor: pointer;
  transition: all 0.15s ease;
  border-bottom: 1px solid #eee;
  background: white;
}

.shipmentItem:last-child {
  border-bottom: none;
}

.shipmentItem:hover {
  background: #f0f7ff;
}

.shipmentItem:active {
  background: #e0efff;
}

.shipmentMain {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 0.35rem;
}

.shipmentDocNo {
  display: flex;
  align-items: center;
  gap: 0.35rem;
  font-weight: 600;
  font-size: 0.9rem;
  color: #333;
}

.shipmentDocNo i {
  color: #667eea;
  font-size: 0.9rem;
}

.shipmentQty {
  display: flex;
  align-items: baseline;
  gap: 0.2rem;
}

.qtyValue {
  font-weight: 700;
  font-size: 1rem;
  color: #f14668;
}

.qtyLabel {
  font-size: 0.7rem;
  color: #888;
}

.shipmentDetails {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  margin-bottom: 0.25rem;
}

.shipmentCustomer,
.shipmentDate {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  font-size: 0.75rem;
  color: #666;
}

.shipmentCustomer {
  flex: 1;
  overflow: hidden;
}

.shipmentCustomer span {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.shipmentCustomer i,
.shipmentDate i {
  color: #999;
  font-size: 0.8rem;
}

.shipmentShipper {
  display: inline-flex;
  align-items: center;
  gap: 0.25rem;
  font-size: 0.7rem;
  color: #3273dc;
  background: #f0f5ff;
  padding: 0.15rem 0.4rem;
  border-radius: 3px;
  margin-top: 0.25rem;
}

.shipmentShipper i {
  font-size: 0.75rem;
}

.shipmentRef {
  display: inline-flex;
  align-items: center;
  gap: 0.25rem;
  font-size: 0.7rem;
  color: #666;
  margin-top: 0.25rem;
  margin-left: 0.5rem;
}

.refLabel {
  color: #999;
}

.refValue {
  font-family: monospace;
}
</style>
