<script setup>
import { string } from 'alga-js'
import { toast } from 'bulma-toast'
import { SelectBox } from 'tedir-select'

const props = defineProps({
  modelValue: Boolean,
  items: Array,
  currency: {
    type: String,
    default: 'EUR'
  },
  defaultHsCode: {
    type: String,
    default: ''
  },
  defaultCountryOfOrigin: {
    type: String,
    default: ''
  },
  defaultCountryOfOriginName: {
    type: String,
    default: ''
  },
  // 'dhl' | 'dpd' — drives carrier-specific fields (Incoterm + EORI for DPD)
  carrier: {
    type: String,
    default: 'dhl'
  },
  // ISO2 destination country — makes the info banner destination-aware
  destinationCountry: {
    type: String,
    default: ''
  },
  // true when the destination is an EU country but outside the EU customs
  // territory (Canary Islands, Ceuta/Melilla, …) — shows an explanation of
  // why customs data is needed despite an EU destination
  isSpecialTerritory: {
    type: Boolean,
    default: false
  }
})

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

const showModal = ref(props.modelValue || false)
watch(() => props.modelValue, () => {
  showModal.value = props.modelValue
  if (props.modelValue) {
    initializeItems()
  }
})

// Initialize customs items from props
const customsItems = ref([])

const initializeItems = () => {
  // Fallback chains (first hit wins):
  // HS code:  M_Product.taricCode → legacy M_Product.CustomsTariffNumber →
  //           hardcoded per-org default → user types it in
  // Origin:   M_Product.C_Country_ID (resolved to alpha-3 by the caller) →
  //           hardcoded per-org default → user picks it
  customsItems.value = (props.items || []).map(item => ({
    item_id: item.item_id,
    product_id: item.product_id,
    description: item.description || '',
    quantity: item.quantity || 1,
    weight: item.weight || 0.1,
    value: item.value || 1,
    hsCode: item.hsCode || item.taricCode || item.customsTariffNumber || props.defaultHsCode || '',
    countryOfOrigin: item.countryOfOrigin || props.defaultCountryOfOrigin || '',
    countryOfOriginName: item.countryOfOriginName || props.defaultCountryOfOriginName || ''
  }))
}

// Country selection
const loading = ref({})
const getOptions = ref({})

const filterCountries = async (key, filter = '') => {
  loading.value[key] = true
  try {
    let url = 'models/c_country'
    if (filter) {
      url = `filters/c_country/${filter}`
    }
    const res = await $fetch('/api/' + url, {
      headers: useRequestHeaders(['cookie'])
    })
    if (res) {
      getOptions.value[key] = res
    }
  } catch (err) {
    console.error('Error loading countries:', err)
  }
  loading.value[key] = false
}

const handleCountryChange = (index, val, opt) => {
  if (opt) {
    customsItems.value[index].countryOfOrigin = opt.ISOCountryCodeAlpha3 || opt.CountryCode || val
    customsItems.value[index].countryOfOriginName = opt.Name || val
  }
}

// Export type options (DHL terminology — DPD uses reasonForExport 01/02/03)
const exportType = ref('COMMERCIAL_GOODS')
const exportTypeOptions = [
  { value: 'COMMERCIAL_GOODS', label: 'Commercial Goods' },
  { value: 'PRESENT', label: 'Gift / Present' },
  { value: 'COMMERCIAL_SAMPLE', label: 'Commercial Sample' },
  { value: 'DOCUMENT', label: 'Document' },
  { value: 'RETURN_OF_GOODS', label: 'Return of Goods' },
  { value: 'OTHER', label: 'Other' }
]

const exportDescription = ref('')

// DPD-specific: Incoterm + Shipper EORI. Only shown when carrier === 'dpd'.
// Default DDP so the sender pays customs (no surprise fees for the recipient).
const dpdIncoterm = ref('DDP')
const dpdIncotermOptions = [
  { value: 'DDP', label: 'DDP — Sender pays duties + taxes (no surprises for recipient)' },
  { value: 'DAP', label: 'DAP — Recipient pays duties + taxes on delivery' },
  { value: 'EXW', label: 'EXW — Recipient handles all formalities (rare)' }
]
// EORI persists across modal opens via localStorage so users don't retype it
const dpdShipperEori = ref(
  typeof window !== 'undefined' ? (localStorage.getItem('commissionDpdShipperEori') || '') : ''
)
watch(dpdShipperEori, (v) => {
  if(typeof window !== 'undefined') localStorage.setItem('commissionDpdShipperEori', v || '')
})

const isDpd = computed(() => String(props.carrier).toLowerCase() === 'dpd')

// Map DHL exportType to DPD reasonForExport for the response payload.
// DHL → DPD: COMMERCIAL_GOODS/OTHER → 01 Sale, PRESENT → 03 Gift, RETURN_OF_GOODS → 02 Return.
const dpdReasonForExport = computed(() => {
  if (exportType.value === 'PRESENT') return '03'
  if (exportType.value === 'RETURN_OF_GOODS') return '02'
  return '01'
})

// Validation
const isValid = computed(() => {
  if (customsItems.value.length === 0) return false

  for (const item of customsItems.value) {
    if (!item.description || item.description.trim() === '') return false
    if (!item.quantity || item.quantity <= 0) return false
    if (!item.value || item.value <= 0) return false
    if (!item.weight || item.weight <= 0) return false
    // hsCode is optional but recommended
    // countryOfOrigin has default
  }

  // If exportType is OTHER, exportDescription is required
  if (exportType.value === 'OTHER' && (!exportDescription.value || exportDescription.value.trim() === '')) {
    return false
  }

  return true
})

const closeModal = () => {
  showModal.value = false
  emit('update:modelValue', false)
}

const confirmCustoms = () => {
  if (!isValid.value) {
    toast({
      message: 'Please fill in all required fields',
      type: 'is-warning',
      duration: 3000
    })
    return
  }

  const customsData = {
    exportType: exportType.value,
    exportDescription: exportType.value === 'OTHER' ? exportDescription.value : undefined,
    items: customsItems.value.map(item => ({
      item_id: item.item_id,
      product_id: item.product_id,
      description: item.description.substring(0, 256), // Max 256 chars
      quantity: parseInt(item.quantity),
      value: parseFloat(item.value),
      weight: parseFloat(item.weight),
      hsCode: item.hsCode ? String(item.hsCode).substring(0, 11) : undefined, // 6-11 chars
      countryOfOrigin: item.countryOfOrigin || 'DEU'
    })),
    // DPD-specific fields. Always emitted (with sensible defaults) so the
    // server can use them when shipping via DPD; ignored by DHL routes.
    incoterm: dpdIncoterm.value,
    reasonForExport: dpdReasonForExport.value,
    shipperEori: dpdShipperEori.value.trim() || undefined
  }

  emit('confirm', customsData)
  closeModal()
}

// Apply same country to all items
const applyCountryToAll = (index) => {
  const sourceItem = customsItems.value[index]
  customsItems.value.forEach((item, i) => {
    if (i !== index) {
      item.countryOfOrigin = sourceItem.countryOfOrigin
      item.countryOfOriginName = sourceItem.countryOfOriginName
    }
  })
  toast({
    message: `Applied "${sourceItem.countryOfOriginName}" to all items`,
    type: 'is-success',
    duration: 2000
  })
}

// Apply same HS code to all items
const applyHsCodeToAll = (index) => {
  const sourceItem = customsItems.value[index]
  if (!sourceItem.hsCode) {
    toast({
      message: 'No HS Code to apply',
      type: 'is-warning',
      duration: 2000
    })
    return
  }
  customsItems.value.forEach((item, i) => {
    if (i !== index) {
      item.hsCode = sourceItem.hsCode
    }
  })
  toast({
    message: `Applied HS Code "${sourceItem.hsCode}" to all items`,
    type: 'is-success',
    duration: 2000
  })
}
</script>

<template>
  <div class="customsModalOverlay" v-if="showModal" @click.self="closeModal">
    <div class="customsModalDialog">
      <div class="customsModalContent">
        <div class="customsModalHeader">
          <h3 class="customsModalTitle">
            <i class="ti ti-file-certificate"></i>
            CN23 Customs Declaration
          </h3>
          <button type="button" class="customsModalClose" @click="closeModal">
            <i class="ti ti-x"></i>
          </button>
        </div>

        <div class="customsModalBody">
          <!-- Export Type Selection -->
          <div class="mb-4 p-3 bg-light rounded">
            <div class="columns">
              <div class="column is-half">
                <div class="legend">
                  <label class="label"><strong>Export Type *</strong></label>
                  <select v-model="exportType" class="select">
                    <option v-for="opt in exportTypeOptions" :key="opt.value" :value="opt.value">
                      {{ opt.label }}
                    </option>
                  </select>
                </div>
              </div>
              <div class="column is-half" v-if="exportType === 'OTHER'">
                <div class="legend">
                  <label class="label"><strong>Export Description *</strong></label>
                  <input type="text" v-model="exportDescription" class="input" placeholder="Describe the export purpose (max 80 chars)" maxlength="80" />
                </div>
              </div>
            </div>
          </div>

          <!-- DPD-specific: Incoterm + Shipper EORI. Only shown when carrier === 'dpd'. -->
          <div v-if="isDpd" class="mb-4 p-3 dpd-customs-section rounded">
            <div class="d-flex items-center gap-10px mb-2 flexWrap-wrap">
              <strong>DPD customs</strong>
              <span class="tag is-warning is-light">DPD only</span>
            </div>
            <div class="columns">
              <div class="column is-half">
                <div class="legend">
                  <label class="label"><strong>Incoterm *</strong></label>
                  <select v-model="dpdIncoterm" class="select">
                    <option v-for="t in dpdIncotermOptions" :key="t.value" :value="t.value">{{ t.label }}</option>
                  </select>
                </div>
              </div>
              <div class="column is-half">
                <div class="legend">
                  <label class="label">
                    <strong>Shipper EORI</strong>
                    <span class="has-text-grey is-size-7">(optional but recommended)</span>
                  </label>
                  <input type="text" v-model="dpdShipperEori" class="input" placeholder="e.g. DE321993855047810" />
                  <p class="help has-text-grey">Saved for next time on this browser.</p>
                </div>
              </div>
            </div>
          </div>

          <!-- Info Banner (destination-aware) -->
          <div class="notification is-info is-light mb-4">
            <p>
              <i class="ti ti-info-circle me-1"></i>
              Please verify and complete the customs information for each item.<template v-if="destinationCountry === 'US'"> HS Codes are mandatory for shipments to the USA.</template>
            </p>
            <p v-if="isSpecialTerritory" class="mt-2">
              <i class="ti ti-map-pin me-1"></i>
              The destination is an EU special territory outside the EU customs/fiscal area
              (e.g. Canary Islands, Ceuta, Melilla) — the carrier requires a customs
              declaration (CN23) even though the country is in the EU.
            </p>
          </div>

          <!-- Items Table -->
          <div class="tableResponsive">
            <table class="table is-fullwidth is-striped">
              <thead>
                <tr>
                  <th style="min-width: 200px;">Description *</th>
                  <th style="width: 80px;">Qty *</th>
                  <th style="width: 100px;">Value ({{ currency }}) *</th>
                  <th style="width: 100px;">Weight (kg) *</th>
                  <th style="min-width: 140px;">HS Code</th>
                  <th style="min-width: 200px;">Country of Origin</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in customsItems" :key="item.item_id || index">
                  <td>
                    <input
                      type="text"
                      v-model="item.description"
                      class="input"
                      :class="{'is-danger': !item.description}"
                      placeholder="Item description"
                      maxlength="256"
                    />
                  </td>
                  <td>
                    <input
                      type="number"
                      v-model="item.quantity"
                      class="input"
                      :class="{'is-danger': !item.quantity || item.quantity <= 0}"
                      min="1"
                    />
                  </td>
                  <td>
                    <input
                      type="number"
                      v-model="item.value"
                      class="input"
                      :class="{'is-danger': !item.value || item.value <= 0}"
                      min="0.01"
                      step="0.01"
                    />
                  </td>
                  <td>
                    <input
                      type="number"
                      v-model="item.weight"
                      class="input"
                      :class="{'is-danger': !item.weight || item.weight <= 0}"
                      min="0.001"
                      step="0.001"
                    />
                  </td>
                  <td>
                    <div class="d-flex gap-1">
                      <input
                        type="text"
                        v-model="item.hsCode"
                        class="input"
                        placeholder="e.g. 84713010"
                        maxlength="11"
                        style="flex: 1;"
                      />
                      <button
                        v-if="customsItems.length > 1"
                        type="button"
                        class="button is-small is-light"
                        @click="applyHsCodeToAll(index)"
                        title="Apply to all items"
                      >
                        <i class="ti ti-copy"></i>
                      </button>
                    </div>
                  </td>
                  <td>
                    <div class="d-flex gap-1">
                      <div style="flex: 1;">
                        <ClientOnly>
                          <SelectBox
                            v-model="item.countryOfOrigin"
                            :options="getOptions?.[`countries_${index}`]?.records || [{ISOCountryCodeAlpha3: item.countryOfOrigin, Name: item.countryOfOriginName}]"
                            prop="Name"
                            dataprop="ISOCountryCodeAlpha3"
                            datatype="string"
                            :size="5"
                            @load="filterCountries(`countries_${index}`)"
                            @search="(val) => filterCountries(`countries_${index}`, string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))"
                            @change="(val, opt) => handleCountryChange(index, val, opt)"
                            :loading="loading?.[`countries_${index}`] ?? false"
                          />
                        </ClientOnly>
                      </div>
                      <button
                        v-if="customsItems.length > 1"
                        type="button"
                        class="button is-small is-light"
                        @click="applyCountryToAll(index)"
                        title="Apply to all items"
                      >
                        <i class="ti ti-copy"></i>
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- Summary -->
          <div class="customsSummary">
            <div class="customsSummaryItem">
              <span class="customsSummaryLabel">Total Items:</span>
              <span class="customsSummaryValue">{{ customsItems.length }}</span>
            </div>
            <div class="customsSummaryItem">
              <span class="customsSummaryLabel">Total Quantity:</span>
              <span class="customsSummaryValue">{{ customsItems.reduce((sum, i) => sum + parseInt(i.quantity || 0), 0) }}</span>
            </div>
            <div class="customsSummaryItem">
              <span class="customsSummaryLabel">Total Value:</span>
              <span class="customsSummaryValue">{{ customsItems.reduce((sum, i) => sum + parseFloat(i.value || 0), 0).toFixed(2) }} {{ currency }}</span>
            </div>
            <div class="customsSummaryItem">
              <span class="customsSummaryLabel">Total Weight:</span>
              <span class="customsSummaryValue">{{ customsItems.reduce((sum, i) => sum + parseFloat(i.weight || 0), 0).toFixed(3) }} kg</span>
            </div>
          </div>
        </div>

        <div class="customsModalFooter">
          <button type="button" class="button is-light" @click="closeModal">
            <i class="ti ti-x me-1"></i> Cancel
          </button>
          <button
            type="button"
            class="button is-success"
            @click="confirmCustoms"
            :disabled="!isValid"
          >
            <i class="ti ti-check me-1"></i> Confirm &amp; Create Label
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* DPD-specific customs section (Incoterm + EORI) */
.dpd-customs-section {
  background: #fff8e1;
  border: 1px solid #ffe082;
}
.gap-10px { gap: 10px; }
.items-center { align-items: center; }
.flexWrap-wrap { flex-wrap: wrap; }

/* Modal Overlay - full screen dark background */
.customsModalOverlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  padding: 20px;
  box-sizing: border-box;
}

/* Modal Dialog - centered container */
.customsModalDialog {
  width: 100%;
  max-width: 1200px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

/* Modal Content - white box */
.customsModalContent {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
  max-height: 90vh;
  overflow-y: auto;
  overflow-x: hidden;
}

/* Modal Header */
.customsModalHeader {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1.25rem 1.5rem;
  border-bottom: 1px solid #e5e5e5;
  background: #f8f9fa;
  border-radius: 8px 8px 0 0;
}

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

.customsModalClose {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  padding: 0.25rem;
  color: #666;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.customsModalClose:hover {
  background-color: #e5e5e5;
  color: #333;
}

/* Modal Body */
.customsModalBody {
  padding: 1.5rem;
  flex: 1;
  position: relative;
  /* Minimum height to prevent collapse, content determines actual height */
  min-height: 300px;
}

/* Modal Footer */
.customsModalFooter {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 1rem;
  padding: 1rem 1.5rem;
  border-top: 1px solid #e5e5e5;
  background: #f8f9fa;
  border-radius: 0 0 8px 8px;
  /* Ensure footer doesn't block dropdowns */
  position: relative;
  z-index: 1;
}

/* Helper classes */
.bg-light {
  background-color: #f5f5f5;
}

.rounded {
  border-radius: 6px;
}

.gap-1 {
  gap: 0.5rem;
}

.mb-4 {
  margin-bottom: 1.5rem;
}

.mt-4 {
  margin-top: 1.5rem;
}

.p-3 {
  padding: 1rem;
}

.me-1 {
  margin-right: 0.25rem;
}

.me-2 {
  margin-right: 0.5rem;
}

/* Table styling */
.tableResponsive {
  overflow-x: auto;
  margin: 0 -0.5rem;
  padding: 0 0.5rem;
}

.table {
  width: 100%;
  border-collapse: collapse;
}

.table th,
.table td {
  padding: 0.75rem 0.5rem;
  vertical-align: middle;
}

.table th {
  text-align: left;
  font-weight: 600;
  white-space: nowrap;
  background: #f8f9fa;
  border-bottom: 2px solid #dee2e6;
}

.table td {
  border-bottom: 1px solid #e9ecef;
}

.table input.input {
  width: 100%;
  min-width: 80px;
}

.table .input {
  padding: 0.5rem 0.75rem;
  font-size: 0.9rem;
}

/* Column widths */
.table th:nth-child(1),
.table td:nth-child(1) {
  min-width: 220px;
}

.table th:nth-child(2),
.table td:nth-child(2) {
  width: 90px;
  min-width: 90px;
}

.table th:nth-child(3),
.table td:nth-child(3),
.table th:nth-child(4),
.table td:nth-child(4) {
  width: 110px;
  min-width: 110px;
}

.table th:nth-child(5),
.table td:nth-child(5) {
  min-width: 160px;
}

.table th:nth-child(6),
.table td:nth-child(6) {
  min-width: 220px;
}

/* Summary section */
.customsSummary {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5rem;
  padding: 1rem;
  background: #f5f5f5;
  border-radius: 6px;
  margin-top: 1.5rem;
}

.customsSummaryItem {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.customsSummaryLabel {
  font-weight: 600;
  color: #555;
}

.customsSummaryValue {
  color: #333;
}

/* Notification styling */
.notification {
  margin-bottom: 1rem;
  padding: 1rem;
  border-radius: 6px;
}

.notification.is-info.is-light {
  background-color: #e8f4fd;
  border: 1px solid #bee5eb;
}

.notification p {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

/* Columns for export type */
.columns {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

.column.is-half {
  flex: 1;
  min-width: 250px;
}

/* Button in table cells */
.d-flex {
  display: flex;
}

.d-flex.gap-1 {
  gap: 0.5rem;
}

.button.is-small {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
}

/* Input validation */
.input.is-danger {
  border-color: #dc3545;
}

/* Select styling */
.select {
  width: 100%;
}

/* Legend styling */
.legend {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.legend .label {
  margin-bottom: 0.25rem;
}

/* Fix SelectBox dropdown z-index issue - ensure dropdown is not clipped by modal overflow */
.customsModalBody :deep(.pickerWrap) {
  position: relative;
}

.customsModalBody :deep(.pickerBody),
.customsModalBody :deep(.pickerContent) {
  position: absolute;
  z-index: 100000 !important;
}

/* Ensure table cells don't clip the dropdown */
.table td:last-child {
  overflow: visible;
  position: relative;
}

/* Table wrapper needs relative position for dropdown to escape */
.tableResponsive {
  overflow: visible;
  position: relative;
}
</style>