<script setup>
import { toast } from 'bulma-toast'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  orderSources: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue'])

const isOpen = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const { t, isGerman } = useTranslation()

// Marketplaces we can generate a real, vendor-accepted flat-file for.
// Add new ones here when their format is implemented in buildFileForMarketplace().
const SUPPORTED_MARKETPLACES = ['amazon']

const marketplaceLabel = (m) => {
  switch ((m || '').toLowerCase()) {
    case 'amazon': return 'Amazon'
    case 'ebay': return 'eBay'
    case 'shopify':
    case 'shopify-new': return 'Shopify'
    case 'temu': return 'Temu'
    case 'jtl-ffn': return 'JTL FFN'
    case 'plenty':
    case 'plentyone': return 'PlentyOne'
    default: return m || 'Unknown'
  }
}

const marketplaceColors = {
  amazon: { bg: '#fff3e0', color: '#ff9900', border: '#ff9900' },
  ebay: { bg: '#e8f0fe', color: '#1a73e8', border: '#1a73e8' },
  shopify: { bg: '#e6f4ea', color: '#1e8e3e', border: '#1e8e3e' },
  'shopify-new': { bg: '#e6f4ea', color: '#1e8e3e', border: '#1e8e3e' },
  temu: { bg: '#ffe6f0', color: '#d81b60', border: '#d81b60' },
  default: { bg: '#f3f4f6', color: '#374151', border: '#9ca3af' },
}
const colorFor = (m) => marketplaceColors[(m || '').toLowerCase()] || marketplaceColors.default

// Form state
const form = ref({
  orderSourceIds: [], // multi-select
  days: 0,            // 0 = today, 1 = last 2 days, 2 = last 3 days
})

const loading = ref(false)
const shippedOrders = ref([])  // raw rows from server, augmented with `selected` + `marketplace`
const currentStep = ref('settings') // 'settings' | 'preview'

// Sort order sources by name
const sortedOrderSources = computed(() => {
  if (!props.orderSources) return []
  return [...props.orderSources].sort((a, b) => {
    const nameA = (a.Name || a.identifier || a.name || '').toLowerCase()
    const nameB = (b.Name || b.identifier || b.name || '').toLowerCase()
    return nameA.localeCompare(nameB)
  })
})

// Resolve marketplace for a given order source object
const marketplaceFor = (os) => (os?.Marketplace?.identifier || os?.marketplace?.identifier || '').toLowerCase()

// Selected sources with marketplace + supported flag, grouped per marketplace
const selectedSummary = computed(() => {
  const groups = {} // marketplace -> { marketplace, supported, sources: [] }
  for (const id of form.value.orderSourceIds) {
    const os = sortedOrderSources.value.find(o => String(o.id) === String(id))
    if (!os) continue
    const m = marketplaceFor(os) || 'unknown'
    if (!groups[m]) {
      groups[m] = { marketplace: m, supported: SUPPORTED_MARKETPLACES.includes(m), sources: [] }
    }
    groups[m].sources.push(os)
  }
  return Object.values(groups)
})

const hasSupportedSelection = computed(() => selectedSummary.value.some(g => g.supported))
const hasUnsupportedSelection = computed(() => selectedSummary.value.some(g => !g.supported))

// Date filter options
const dateOptions = [
  { value: 0, label: isGerman.value ? 'Heute' : 'Today' },
  { value: 1, label: isGerman.value ? 'Letzte 2 Tage' : 'Last 2 days' },
  { value: 2, label: isGerman.value ? 'Letzte 3 Tage' : 'Last 3 days' },
  { value: 6, label: isGerman.value ? 'Letzte 7 Tage' : 'Last 7 days' },
  { value: 13, label: isGerman.value ? 'Letzte 14 Tage' : 'Last 14 days' },
  { value: 29, label: isGerman.value ? 'Letzte 30 Tage' : 'Last 30 days' },
]

// Carrier name → Amazon carrier-code (whitelist from Amazon template)
const carrierCodeMap = {
  'dhl ecommerce': 'DHL eCommerce',
  'dhl freight': 'DHL Freight',
  'dhl home delivery': 'DHL Home Delivery',
  'deutsche post': 'Deutsche Post',
  'dhl': 'DHL',
  'dpd': 'DPD',
  'gls': 'GLS',
  'hermes einrichtungsservice': 'Hermes Einrichtungsservice',
  'hermes': 'Hermes Logistik Gruppe',
  'ups': 'UPS',
  'fedex': 'FedEx',
  'tnt': 'TNT',
  'post nl': 'Post NL',
  'postnl': 'Post NL',
  'royal mail': 'Royal Mail',
  'la poste': 'La Poste',
  'chronopost': 'Chronopost',
  'gel express': 'GEL Express',
  'parcelforce': 'Parcelforce',
  'asendia': 'Asendia',
  'go!': 'GO!',
  'yodel': 'Yodel',
  'rhenus': 'Rhenus',
  'db schenker': 'DB Schenker',
  'kuehne+nagel': 'Kuehne+Nagel',
}

const getCarrierCode = (shipperName) => {
  if (!shipperName) return 'Other'
  const lower = shipperName.toLowerCase().trim()
  // Longest-key-first so "dhl ecommerce" wins over "dhl"
  const keys = Object.keys(carrierCodeMap).sort((a, b) => b.length - a.length)
  for (const key of keys) {
    if (lower.includes(key)) return carrierCodeMap[key]
  }
  return 'Other'
}

const getCarrierName = (shipperName, carrierCode) => carrierCode === 'Other' ? (shipperName || '') : ''

// Fetch shipped orders for ALL selected supported sources
const fetchOrders = async () => {
  const supportedIds = []
  for (const id of form.value.orderSourceIds) {
    const os = sortedOrderSources.value.find(o => String(o.id) === String(id))
    if (os && SUPPORTED_MARKETPLACES.includes(marketplaceFor(os))) {
      supportedIds.push(id)
    }
  }

  if (supportedIds.length === 0) {
    toast({
      message: isGerman.value
        ? 'Bitte mindestens eine Auftragsquelle mit unterstütztem Marktplatz auswählen'
        : 'Please select at least one order source with a supported marketplace',
      type: 'is-warning', duration: 3000
    })
    return
  }

  loading.value = true
  try {
    const res = await $fetch('/api/orders/shipping-confirmations', {
      params: {
        orderSourceIds: supportedIds.join(','),
        days: form.value.days,
      }
    })

    if (res?.records?.length > 0) {
      shippedOrders.value = res.records.map(r => ({ ...r, selected: true }))
      currentStep.value = 'preview'
      toast({
        message: isGerman.value
          ? `${res.records.length} versendete Aufträge gefunden`
          : `Found ${res.records.length} shipped order(s)`,
        type: 'is-success', duration: 3000
      })
    } else {
      toast({
        message: isGerman.value
          ? 'Keine versendeten Aufträge für die ausgewählten Kriterien gefunden'
          : 'No shipped orders found for the selected criteria',
        type: 'is-info', duration: 3000
      })
    }
  } catch (error) {
    console.error('Error fetching shipped orders:', error)
    toast({ message: 'Error fetching shipped orders', type: 'is-danger', duration: 5000 })
  } finally {
    loading.value = false
  }
}

// Group preview rows by marketplace
const ordersByMarketplace = computed(() => {
  const groups = {}
  for (const o of shippedOrders.value) {
    const m = o.marketplace || 'unknown'
    if (!groups[m]) groups[m] = []
    groups[m].push(o)
  }
  return Object.entries(groups).map(([marketplace, orders]) => ({ marketplace, orders }))
})

const selectedCount = computed(() => shippedOrders.value.filter(o => o.selected).length)

const toggleGroup = (orders, value) => {
  for (const o of orders) o.selected = value
}

// Build the Amazon flat-file (tab-separated, full 18-column header) for the given orders
const buildAmazonFile = (orders) => {
  const headers = [
    'order-id', 'order-item-id', 'quantity', 'ship-date',
    'carrier-code', 'carrier-name', 'tracking-number', 'ship-method',
    'transparency_code',
    'ship_from_address_name', 'ship_from_address_line1', 'ship_from_address_line2',
    'ship_from_address_line3', 'ship_from_address_city', 'ship_from_address_county',
    'ship_from_address_state_or_region', 'ship_from_address_postalcode', 'ship_from_address_countrycode',
  ]
  const lines = [headers.join('\t')]

  for (const order of orders) {
    const totalQty = (order.orderLines || []).reduce(
      (sum, l) => sum + Number(l.qtyDelivered || l.qty || 0), 0
    )
    // One row per shipment. order-item-id is left blank; Amazon treats this as
    // a full-order confirmation when the order ships in a single parcel.
    for (const shipment of (order.shipments || [])) {
      const carrierCode = getCarrierCode(shipment.shipperName)
      const carrierName = getCarrierName(shipment.shipperName, carrierCode)
      const shipDate = shipment.shippingDate
        ? new Date(shipment.shippingDate).toISOString().split('T')[0]
        : new Date().toISOString().split('T')[0]

      const row = [
        order.externalOrderId || '',
        '', // order-item-id (not stored on import)
        totalQty || '',
        shipDate,
        carrierCode,
        carrierName,
        shipment.trackingNo || '',
        shipment.shippingServiceName || shipment.shipperName || '',
        '', // transparency_code
        '', '', '', '', '', '', '', '', '', // ship_from_address_*
      ]
      // Strip tabs/newlines inside any cell to keep the TSV well-formed
      lines.push(row.map(v => String(v).replace(/[\t\r\n]+/g, ' ')).join('\t'))
    }
  }

  return lines.join('\n') + '\n'
}

const buildFileForMarketplace = (marketplace, orders) => {
  if (marketplace === 'amazon') return buildAmazonFile(orders)
  return null
}

const triggerDownload = (content, filename) => {
  const blob = new Blob([content], { type: 'text/tab-separated-values;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

const downloadFiles = () => {
  const selected = shippedOrders.value.filter(o => o.selected)
  if (selected.length === 0) {
    toast({
      message: isGerman.value ? 'Keine Zeilen ausgewählt' : 'No rows selected',
      type: 'is-warning', duration: 3000
    })
    return
  }

  const grouped = {}
  for (const o of selected) {
    const m = o.marketplace || 'unknown'
    if (!grouped[m]) grouped[m] = []
    grouped[m].push(o)
  }

  const dateStr = new Date().toISOString().split('T')[0]
  let filesProduced = 0
  const skipped = []

  for (const [marketplace, orders] of Object.entries(grouped)) {
    const content = buildFileForMarketplace(marketplace, orders)
    if (!content) {
      skipped.push(marketplace)
      continue
    }
    triggerDownload(content, `${marketplace}-shipping-confirmation-${dateStr}.txt`)
    filesProduced++
  }

  if (filesProduced > 0) {
    toast({
      message: isGerman.value
        ? `${filesProduced} Datei(en) für ${selected.length} Zeile(n) heruntergeladen`
        : `Downloaded ${filesProduced} file(s) for ${selected.length} row(s)`,
      type: 'is-success', duration: 4000
    })
  }
  if (skipped.length) {
    toast({
      message: (isGerman.value ? 'Übersprungen (nicht unterstützt): ' : 'Skipped (not supported): ') + skipped.map(marketplaceLabel).join(', '),
      type: 'is-warning', duration: 5000
    })
  }
}

// Reset and close
const handleClose = () => {
  isOpen.value = false
  currentStep.value = 'settings'
  form.value = { orderSourceIds: [], days: 0 }
  shippedOrders.value = []
}

const goBack = () => {
  currentStep.value = 'settings'
  shippedOrders.value = []
}
</script>

<template>
  <div class="modal-overlay" v-if="isOpen">
    <div class="modal-wrapper" @click.self="handleClose">
      <div class="modalContent">
        <div class="modalHeader">
          <h3 class="modalTitle">
            <span class="ti ti-truck-delivery me-2"></span>
            {{ isGerman ? 'Versandbestätigungen' : 'Shipping Confirmations' }}
          </h3>
          <div class="cursor-pointer" @click="handleClose">
            <span class="tf-icon ti ti-x ti-sm me-1"></span>
          </div>
        </div>

        <div class="modalBody">
          <!-- Step 1: Settings -->
          <div v-if="currentStep === 'settings'" class="my-4 mx-4">
            <p class="mb-4" style="color: #6b7280; font-size: 0.875rem;">
              {{ isGerman
                ? 'Versandbestätigungen für Marktplatz-Aufträge generieren. Wählen Sie eine oder mehrere Auftragsquellen und einen Zeitraum.'
                : 'Generate shipping confirmation files for marketplace orders. Pick one or more order sources and a date range.' }}
            </p>

            <!-- Multi-select Order Sources -->
            <div class="field mb-4">
              <label class="label">{{ isGerman ? 'Auftragsquellen' : 'Order Sources' }}</label>
              <div class="sources-list">
                <label
                  v-for="os in sortedOrderSources"
                  :key="os.id"
                  class="source-item"
                  :class="{ 'is-checked': form.orderSourceIds.includes(os.id) }"
                >
                  <input type="checkbox" :value="os.id" v-model="form.orderSourceIds" />
                  <span class="source-name">{{ os.Name || os.identifier || os.name }}</span>
                  <span
                    v-if="marketplaceFor(os)"
                    class="marketplace-badge"
                    :style="{ backgroundColor: colorFor(marketplaceFor(os)).bg, color: colorFor(marketplaceFor(os)).color, borderColor: colorFor(marketplaceFor(os)).border }"
                  >
                    {{ marketplaceLabel(marketplaceFor(os)) }}
                  </span>
                </label>
                <div v-if="sortedOrderSources.length === 0" class="has-text-grey is-size-7 px-3 py-2">
                  {{ isGerman ? 'Keine Auftragsquellen verfügbar' : 'No order sources available' }}
                </div>
              </div>
            </div>

            <!-- Marketplace support notice -->
            <div v-if="selectedSummary.length > 0" class="notice mb-4">
              <div class="notice-title">
                {{ isGerman ? 'Marktplatz-Unterstützung' : 'Marketplace support' }}
              </div>
              <ul class="notice-list">
                <li v-for="g in selectedSummary" :key="g.marketplace">
                  <span class="ti me-1" :class="g.supported ? 'ti-check has-text-success' : 'ti-alert-triangle has-text-warning'"></span>
                  <strong>{{ marketplaceLabel(g.marketplace) }}</strong>
                  <span class="has-text-grey">
                    — {{ g.sources.length }} {{ isGerman ? 'Quelle(n)' : 'source(s)' }}
                  </span>
                  <span v-if="!g.supported" class="ml-2 has-text-grey-dark is-size-7">
                    {{ isGerman ? 'kein Bestätigungsformat hinterlegt — wird übersprungen' : 'no confirmation format implemented — will be skipped' }}
                  </span>
                </li>
              </ul>
              <p v-if="hasUnsupportedSelection" class="help mt-2">
                {{ isGerman
                  ? 'Aktuell wird nur das Amazon-Flat-File-Format generiert. Weitere Marktplätze können in dieser Komponente nachgepflegt werden.'
                  : 'Only the Amazon flat-file format is generated right now. Other marketplaces can be added in this component.' }}
              </p>
            </div>

            <!-- Date Range Selection -->
            <div class="field mb-4">
              <label class="label">{{ isGerman ? 'Zeitraum' : 'Date Range' }}</label>
              <div class="control">
                <div class="select is-fullwidth">
                  <select v-model="form.days">
                    <option v-for="opt in dateOptions" :key="opt.value" :value="opt.value">
                      {{ opt.label }}
                    </option>
                  </select>
                </div>
              </div>
              <p class="help">{{ isGerman ? 'Filter nach Versanddatum' : 'Filter by shipping date' }}</p>
            </div>
          </div>

          <!-- Step 2: Preview -->
          <div v-else-if="currentStep === 'preview'" class="my-4 mx-2">
            <div class="d-flex justify-between items-center mb-3 mx-2">
              <div class="d-flex items-center gap-10px">
                <button class="button is-small" @click="goBack">
                  <span class="ti ti-arrow-left me-1"></span>
                  {{ isGerman ? 'Zurück' : 'Back' }}
                </button>
                <span class="tag is-info">
                  {{ selectedCount }} / {{ shippedOrders.length }}
                  {{ isGerman ? 'ausgewählt' : 'selected' }}
                </span>
              </div>
            </div>

            <div v-for="group in ordersByMarketplace" :key="group.marketplace" class="marketplace-group mx-2 mb-4">
              <div class="marketplace-group-header">
                <span
                  class="marketplace-badge"
                  :style="{ backgroundColor: colorFor(group.marketplace).bg, color: colorFor(group.marketplace).color, borderColor: colorFor(group.marketplace).border }"
                >
                  {{ marketplaceLabel(group.marketplace) }}
                </span>
                <span class="ml-2 is-size-7 has-text-grey">{{ group.orders.length }} {{ isGerman ? 'Auftrag/Aufträge' : 'order(s)' }}</span>
                <div class="ml-auto buttons are-small">
                  <button class="button is-small" @click="toggleGroup(group.orders, true)">{{ isGerman ? 'Alle' : 'All' }}</button>
                  <button class="button is-small" @click="toggleGroup(group.orders, false)">{{ isGerman ? 'Keine' : 'None' }}</button>
                </div>
              </div>

              <div class="orders-preview-table">
                <table class="table is-fullwidth is-hoverable is-size-7">
                  <thead>
                    <tr>
                      <th style="width: 30px;"></th>
                      <th>{{ isGerman ? 'Auftrag-Nr.' : 'Order #' }}</th>
                      <th>{{ isGerman ? 'Externe Auftrag-ID' : 'External Order ID' }}</th>
                      <th>{{ isGerman ? 'Datum' : 'Date' }}</th>
                      <th>{{ isGerman ? 'Zeilen' : 'Lines' }}</th>
                      <th>{{ isGerman ? 'Tracking' : 'Tracking' }}</th>
                      <th>{{ isGerman ? 'Carrier' : 'Carrier' }}</th>
                      <th>{{ isGerman ? 'Versanddatum' : 'Ship Date' }}</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(order, idx) in group.orders" :key="idx" :class="{ 'row-unchecked': !order.selected }">
                      <td><input type="checkbox" v-model="order.selected" /></td>
                      <td><span class="tag is-light">{{ order.documentNo }}</span></td>
                      <td><strong>{{ order.externalOrderId }}</strong></td>
                      <td><small>{{ order.dateOrdered ? new Date(order.dateOrdered).toLocaleDateString('de-DE') : '' }}</small></td>
                      <td>
                        <div v-for="(line, li) in order.orderLines" :key="li">
                          <small>{{ line.productValue }} - {{ line.productName?.substring(0, 30) }} (x{{ line.qtyDelivered || line.qty }})</small>
                        </div>
                      </td>
                      <td>
                        <div v-for="(ship, si) in order.shipments" :key="si">
                          <span class="tag is-success is-light">{{ ship.trackingNo }}</span>
                        </div>
                      </td>
                      <td>
                        <div v-for="(ship, si) in order.shipments" :key="si">
                          <small>{{ ship.shipperName || 'N/A' }}</small>
                        </div>
                      </td>
                      <td>
                        <div v-for="(ship, si) in order.shipments" :key="si">
                          <small>{{ ship.shippingDate ? new Date(ship.shippingDate).toLocaleDateString('de-DE') : '' }}</small>
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>

        <div class="modalFooter">
          <div class="buttons" style="margin-left: auto;">
            <button class="button" @click="handleClose">
              {{ isGerman ? 'Abbrechen' : 'Cancel' }}
            </button>

            <button
              v-if="currentStep === 'settings'"
              class="button is-primary"
              :class="{ 'is-loading': loading }"
              :disabled="!hasSupportedSelection"
              @click="fetchOrders"
            >
              <span class="ti ti-eye me-1"></span>
              {{ isGerman ? 'Vorschau' : 'Preview' }}
            </button>

            <button
              v-if="currentStep === 'preview'"
              class="button is-success"
              :disabled="selectedCount === 0"
              @click="downloadFiles"
            >
              <span class="ti ti-download me-1"></span>
              {{ isGerman ? 'Versandbestätigungen herunterladen' : 'Download Shipping Confirmations' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.modalContent {
  max-width: 95vw;
  width: 100%;
  max-height: 95vh;
  overflow-y: auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modalHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 1.5rem;
  border-bottom: 1px solid #e5e7eb;
  background: #f9fafb;
  border-radius: 8px 8px 0 0;
}

.modalTitle {
  font-size: 1.25rem;
  font-weight: 600;
  margin: 0;
  display: flex;
  align-items: center;
}

.modalBody {
  padding: 0;
  max-height: calc(95vh - 140px);
  overflow-y: auto;
}

.modalFooter {
  display: flex;
  justify-content: flex-end;
  padding: 1rem 1.5rem;
  border-top: 1px solid #e5e7eb;
  background: #f9fafb;
  border-radius: 0 0 8px 8px;
}

.marketplace-badge {
  display: inline-flex;
  align-items: center;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.75rem;
  font-weight: 600;
  border: 1px solid;
  white-space: nowrap;
}

.sources-list {
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  max-height: 260px;
  overflow-y: auto;
  background: #fff;
}

.source-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 0.75rem;
  border-bottom: 1px solid #f3f4f6;
  cursor: pointer;
  font-size: 0.875rem;
}

.source-item:last-child { border-bottom: none; }
.source-item:hover { background: #f9fafb; }
.source-item.is-checked { background: #eff6ff; }
.source-item .source-name { flex: 1; }

.notice {
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: #f9fafb;
  padding: 0.75rem 1rem;
}

.notice-title {
  font-weight: 600;
  font-size: 0.875rem;
  margin-bottom: 0.5rem;
}

.notice-list {
  list-style: none;
  margin: 0;
  padding: 0;
  font-size: 0.85rem;
}

.notice-list li {
  padding: 2px 0;
}

.marketplace-group {
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  overflow: hidden;
}

.marketplace-group-header {
  display: flex;
  align-items: center;
  padding: 0.5rem 0.75rem;
  background: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
}

.orders-preview-table {
  max-height: 380px;
  overflow-y: auto;
}

.orders-preview-table .table {
  margin-bottom: 0;
}

.orders-preview-table .table thead {
  position: sticky;
  top: 0;
  background: #f9fafb;
  z-index: 1;
}

.orders-preview-table .table th {
  border-bottom: 2px solid #e5e7eb;
  white-space: nowrap;
}

.orders-preview-table .table td {
  vertical-align: middle;
}

.row-unchecked {
  opacity: 0.45;
}
</style>
