<script setup>
const props = defineProps({
  params: Object
})

const showModal = ref(false)
const feeLines = ref(null)
const isLoading = ref(false)

const fetchFeeLines = async () => {
  isLoading.value = true
  showModal.value = true

  try {
    // Build filter query to match either C_Order_ID or any M_InOut_ID
    const orderId = props.params.data.id
    const shipments = props.params.data.minout || []

    // Create filter parts
    const filterParts = [`C_Order_ID eq ${orderId}`]

    // Add M_InOut_ID filters for each shipment
    if (shipments.length > 0) {
      shipments.forEach(shipment => {
        if (shipment.id) {
          filterParts.push(`M_InOut_ID eq ${shipment.id}`)
        }
      })
    }

    // Join with OR
    const filter = filterParts.join(' OR ')

    const res = await $fetch(`/api/fulfillment-fees?filter=${encodeURIComponent(filter)}`, {
      headers: useRequestHeaders(['cookie'])
    })
    console.log('Fee lines:', res)

    // Fetch shipping fee details for shippingfee type records
    if (res?.records) {
      for (const record of res.records) {
        if (record.FulfillTypeAccounting === 'shippingfee' && record.M_InOut_ID?.id) {
          try {
            const shippingDetails = await $fetch(`/api/shipments/${record.M_InOut_ID.id}/shipping-fees`, {
              headers: useRequestHeaders(['cookie'])
            })
            record.shippingFeeDetails = shippingDetails
          } catch (err) {
            console.error(`Failed to fetch shipping details for inout ${record.M_InOut_ID.id}:`, err)
          }
        }
      }
    }

    feeLines.value = res
  } catch (error) {
    console.error('Failed to fetch fee lines:', error)
    feeLines.value = { error: 'Failed to load data' }
  } finally {
    isLoading.value = false
  }
}

const closeModal = () => {
  showModal.value = false
  feeLines.value = null
}

// Helper function to get value with case-insensitive property access
const getFieldValue = (record, fieldName) => {
  if (record[fieldName] !== undefined) {
    return record[fieldName]
  }
  const lowerField = fieldName.toLowerCase()
  if (record[lowerField] !== undefined) {
    return record[lowerField]
  }
  const keys = Object.keys(record)
  const matchingKey = keys.find(k => k.toLowerCase() === lowerField)
  if (matchingKey) {
    return record[matchingKey]
  }
  return undefined
}

// Helper function to get color class based on type
const getTypeClass = (type) => {
  switch (type?.toLowerCase()) {
    case 'shippingfee':
      return 'is-info'
    case 'fulfillment':
      return 'is-success'
    default:
      return 'is-light'
  }
}
</script>

<template>
  <div class="button-container">
    <button
      @click="fetchFeeLines"
      class="icon-button"
      title="View related fee lines"
    >
      <i class="ti ti-list-details"></i>
    </button>
  </div>

  <!-- Modal -->
  <Teleport to="body">
    <div v-if="showModal" class="modal is-active">
      <div class="modal-background" @click="closeModal"></div>
      <div class="modal-card" style="width: 90%; max-width: 1200px;">
        <header class="modal-card-head">
          <p class="modal-card-title">Fee Lines - Order #{{ props.params.data.documentNo }}</p>
          <button class="delete" aria-label="close" @click="closeModal"></button>
        </header>
        <section class="modal-card-body">
          <div v-if="isLoading" class="has-text-centered">
            <span class="loader"></span>
            <p class="mt-3">Loading...</p>
          </div>
          <div v-else-if="feeLines?.error" class="notification is-danger">
            {{ feeLines.error }}
          </div>
          <div v-else-if="feeLines?.records && feeLines.records.length > 0">
            <div class="mb-4">
              <strong>Total Records:</strong> {{ feeLines['row-count'] }}
            </div>

            <div v-for="(record, index) in feeLines.records" :key="record.id" class="box mb-4">
              <div class="columns is-multiline">
                <div class="column is-12">
                  <h3 class="title is-5">Line #{{ index + 1 }}</h3>
                </div>

                <div class="column is-6">
                  <p><strong>ID:</strong> {{ record.id }}</p>
                  <p><strong>Product:</strong> {{ record.M_Product_ID?.identifier || 'N/A' }}</p>
                  <p><strong>Shipment Line:</strong> {{ record.M_InOutLine_ID?.identifier || 'N/A' }}</p>
                  <p><strong>Shipment:</strong> {{ record.M_InOut_ID?.identifier || 'N/A' }}</p>
                  <p v-if="record.C_Order_ID"><strong>Order:</strong> {{ record.C_Order_ID?.identifier || 'N/A' }}</p>
                  <p v-if="record.C_BPartner_ID"><strong>Business Partner:</strong> {{ record.C_BPartner_ID?.identifier || 'N/A' }}</p>
                </div>

                <div class="column is-6">
                  <p><strong>Organization:</strong> {{ record.AD_Org_ID?.identifier || 'N/A' }}</p>
                  <p><strong>Created:</strong> {{ new Date(record.Created).toLocaleString() }}</p>
                  <p><strong>Active:</strong> {{ record.IsActive ? 'Yes' : 'No' }}</p>
                  <p><strong>Processed:</strong> {{ record.Processed ? 'Yes' : 'No' }}</p>
                  <p v-if="record.shipping_date"><strong>Shipping Date:</strong> {{ new Date(record.shipping_date).toLocaleString() }}</p>
                  <p v-if="record.FulfillTypeAccounting">
                    <strong>Type:</strong>
                    <span :class="['tag', getTypeClass(record.FulfillTypeAccounting)]">
                      {{ record.FulfillTypeAccounting }}
                    </span>
                  </p>
                </div>

                <div class="column is-12">
                  <hr class="my-3">
                  <h4 class="title is-6">Pricing Details</h4>
                </div>

                <div class="column is-3">
                  <p><strong>Qty Entered:</strong> {{ getFieldValue(record, 'QtyEntered') || getFieldValue(record, 'qtyEntered') || 0 }}</p>
                  <p><strong>Qty Invoiced:</strong> {{ getFieldValue(record, 'QtyInvoiced') || getFieldValue(record, 'qtyInvoiced') || 0 }}</p>
                  <p v-if="getFieldValue(record, 'PriceEntered')"><strong>Price Entered:</strong> {{ (getFieldValue(record, 'PriceEntered') || 0).toFixed(2) }}</p>
                </div>

                <div class="column is-3">
                  <p><strong>Base Price:</strong> {{ (getFieldValue(record, 'FulfillmentBasePrice') || getFieldValue(record, 'fulfillmentBasePrice') || 0).toFixed(2) }}</p>
                  <p><strong>Once Fee:</strong> {{ (getFieldValue(record, 'FulfillOnceFee') || getFieldValue(record, 'fulfillOnceFee') || 0).toFixed(2) }}</p>
                </div>

                <div class="column is-3">
                  <p><strong>Pick Unit Price:</strong> {{ (getFieldValue(record, 'FulfillmentPickUnitPrice') || getFieldValue(record, 'fulfillmentPickUnitPrice') || 0).toFixed(2) }}</p>
                  <p><strong>Material Costs:</strong> {{ (getFieldValue(record, 'FulfillMaterialCosts') || getFieldValue(record, 'fulfillMaterialCosts') || 0).toFixed(2) }}</p>
                </div>

                <div class="column is-3">
                  <p><strong>Pick Qty:</strong> {{ getFieldValue(record, 'FulfillmentPickQty') || getFieldValue(record, 'fulfillmentPickQty') || 0 }}</p>
                  <p><strong>Pick Total:</strong> {{ (getFieldValue(record, 'FulfillmentPickTotalPrice') || getFieldValue(record, 'fulfillmentPickTotalPrice') || 0).toFixed(2) }}</p>
                </div>

                <div class="column is-3">
                  <p><strong>Pricing Rule:</strong> {{ record.FulfillmentPricingRule || 'N/A' }}</p>
                  <p class="has-text-weight-bold has-text-primary"><strong>Line Total:</strong> {{ record.LineTotalAmt?.toFixed(2) || '0.00' }}</p>
                </div>

                <!-- Shipping Fee Details Section -->
                <template v-if="record.FulfillTypeAccounting === 'shippingfee' && record.shippingFeeDetails">
                  <div class="column is-12">
                    <hr class="my-3">
                    <h4 class="title is-6">Shipping Fee Details</h4>
                  </div>

                  <!-- General Info -->
                  <div class="column is-12">
                    <div class="columns">
                      <div class="column is-4">
                        <p><strong>Service:</strong> {{ record.shippingFeeDetails.shipping_service_name || 'N/A' }}</p>
                        <p><strong>Paket Type:</strong> {{ record.shippingFeeDetails.M_Paket_Type_ID?.Name || 'N/A' }}</p>
                      </div>
                      <div class="column is-4">
                        <p><strong>DHL Product ID:</strong> {{ record.shippingFeeDetails.dhl_product_id || 'N/A' }}</p>
                        <p><strong>DHL Product:</strong> {{ record.shippingFeeDetails.dhl_product_description || 'N/A' }}</p>
                      </div>
                      <div class="column is-4">
                        <p><strong>Weight:</strong> {{ record.shippingFeeDetails.ext_freight_weight != null ? `${record.shippingFeeDetails.ext_freight_weight} kg` : 'N/A' }}</p>
                        <p><strong>DHL Klein Paket:</strong> {{ record.shippingFeeDetails.isDHLKleinPaket ? 'Yes' : 'No' }}</p>
                      </div>
                    </div>
                  </div>

                  <!-- External vs Internal Comparison -->
                  <div class="column is-12">
                    <div class="box has-background-light">
                      <table class="table is-fullwidth is-striped">
                        <thead>
                          <tr>
                            <th>Metric</th>
                            <th class="has-text-right">External</th>
                            <th class="has-text-right">Internal</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr>
                            <td><strong>Total</strong></td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.ext_freight_total != null ? record.shippingFeeDetails.ext_freight_total.toFixed(2) + ' €' : 'N/A' }}</td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.int_freight_total != null ? record.shippingFeeDetails.int_freight_total.toFixed(2) + ' €' : 'N/A' }}</td>
                          </tr>
                          <tr>
                            <td><strong>Cost</strong></td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.ext_freight_cost != null ? record.shippingFeeDetails.ext_freight_cost.toFixed(2) + ' €' : 'N/A' }}</td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.int_freight_cost != null ? record.shippingFeeDetails.int_freight_cost.toFixed(2) + ' €' : 'N/A' }}</td>
                          </tr>
                          <tr>
                            <td><strong>CO2</strong></td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.ext_freight_co2 != null ? record.shippingFeeDetails.ext_freight_co2.toFixed(2) + ' €' : 'N/A' }}</td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.int_freight_co2 != null ? record.shippingFeeDetails.int_freight_co2.toFixed(2) + ' €' : 'N/A' }}</td>
                          </tr>
                          <tr>
                            <td><strong>Energy</strong></td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.ext_freight_energy != null ? record.shippingFeeDetails.ext_freight_energy.toFixed(2) + ' €' : 'N/A' }}</td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.int_freight_energy != null ? record.shippingFeeDetails.int_freight_energy.toFixed(2) + ' €' : 'N/A' }}</td>
                          </tr>
                          <tr>
                            <td><strong>Peak</strong></td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.ext_freight_peak != null ? record.shippingFeeDetails.ext_freight_peak.toFixed(2) + ' €' : 'N/A' }}</td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.int_freight_peak != null ? record.shippingFeeDetails.int_freight_peak.toFixed(2) + ' €' : 'N/A' }}</td>
                          </tr>
                          <tr>
                            <td><strong>Others</strong></td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.ext_freight_others != null ? record.shippingFeeDetails.ext_freight_others.toFixed(2) + ' €' : 'N/A' }}</td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.int_freight_others != null ? record.shippingFeeDetails.int_freight_others.toFixed(2) + ' €' : 'N/A' }}</td>
                          </tr>
                          <tr>
                            <td><strong>Insurance</strong></td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.ext_freight_insurance != null ? record.shippingFeeDetails.ext_freight_insurance.toFixed(2) + ' €' : 'N/A' }}</td>
                            <td class="has-text-right">—</td>
                          </tr>
                          <tr>
                            <td><strong>Return Fees</strong></td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.ext_freight_returnfees != null ? record.shippingFeeDetails.ext_freight_returnfees.toFixed(2) + ' €' : 'N/A' }}</td>
                            <td class="has-text-right">—</td>
                          </tr>
                          <tr>
                            <td><strong>Codierung</strong></td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.ext_freight_codierung != null ? record.shippingFeeDetails.ext_freight_codierung.toFixed(2) + ' €' : 'N/A' }}</td>
                            <td class="has-text-right">—</td>
                          </tr>
                          <tr>
                            <td><strong>Int. Premium</strong></td>
                            <td class="has-text-right">{{ record.shippingFeeDetails.ext_freight_intpremium != null ? record.shippingFeeDetails.ext_freight_intpremium.toFixed(2) + ' €' : 'N/A' }}</td>
                            <td class="has-text-right">—</td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>

                  <!-- Status Flags -->
                  <div class="column is-12">
                    <div class="tags">
                      <span :class="['tag', record.shippingFeeDetails.IsCommissioned ? 'is-success' : 'is-light']">
                        <strong>Commissioned:</strong>&nbsp;{{ record.shippingFeeDetails.IsCommissioned ? 'Yes' : 'No' }}
                      </span>
                      <span :class="['tag', record.shippingFeeDetails.IsCommissionedConfirmed ? 'is-success' : 'is-light']">
                        <strong>Confirmed:</strong>&nbsp;{{ record.shippingFeeDetails.IsCommissionedConfirmed ? 'Yes' : 'No' }}
                      </span>
                      <span :class="['tag', record.shippingFeeDetails.ack_commissioned_laravel ? 'is-success' : 'is-light']">
                        <strong>Laravel ACK:</strong>&nbsp;{{ record.shippingFeeDetails.ack_commissioned_laravel ? 'Yes' : 'No' }}
                      </span>
                      <span :class="['tag', record.shippingFeeDetails.isplentyinprogress ? 'is-warning' : 'is-light']">
                        <strong>Plenty In Progress:</strong>&nbsp;{{ record.shippingFeeDetails.isplentyinprogress ? 'Yes' : 'No' }}
                      </span>
                      <span :class="['tag', record.shippingFeeDetails.isAccountingExported ? 'is-success' : 'is-light']">
                        <strong>Accounting Exported:</strong>&nbsp;{{ record.shippingFeeDetails.isAccountingExported ? 'Yes' : 'No' }}
                      </span>
                      <span :class="['tag', record.shippingFeeDetails.isExportedPaketAccounting ? 'is-success' : 'is-light']">
                        <strong>Paket Accounting:</strong>&nbsp;{{ record.shippingFeeDetails.isExportedPaketAccounting ? 'Yes' : 'No' }}
                      </span>
                      <span :class="['tag', record.shippingFeeDetails.isExternalFeeAccounted ? 'is-success' : 'is-light']">
                        <strong>External Fee Accounted:</strong>&nbsp;{{ record.shippingFeeDetails.isExternalFeeAccounted ? 'Yes' : 'No' }}
                      </span>
                      <span :class="['tag', record.shippingFeeDetails.isShippingFeeAccounted ? 'is-success' : 'is-light']">
                        <strong>Shipping Fee Accounted:</strong>&nbsp;{{ record.shippingFeeDetails.isShippingFeeAccounted ? 'Yes' : 'No' }}
                      </span>
                    </div>
                  </div>
                </template>
              </div>
            </div>

            <div class="box has-background-primary-light">
              <div class="columns">
                <div class="column is-12">
                  <p class="title is-4 has-text-primary">
                    Grand Total: {{ feeLines.records.reduce((sum, r) => sum + (r.LineTotalAmt || 0), 0).toFixed(2) }} {{ props.params.data.currency }}
                  </p>
                </div>
              </div>
            </div>

            <details class="mt-4">
              <summary class="button is-small is-light">View Raw JSON</summary>
              <pre class="mt-2" style="max-height: 400px; overflow: auto;">{{ JSON.stringify(feeLines, null, 2) }}</pre>
            </details>
          </div>
          <div v-else-if="feeLines?.records && feeLines.records.length === 0" class="notification is-info">
            No fee lines found for this order.
          </div>
        </section>
        <footer class="modal-card-foot">
          <button class="button" @click="closeModal">Close</button>
        </footer>
      </div>
    </div>
  </Teleport>
</template>

<style scoped>
.button-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.icon-button {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  margin: 0;
  color: #3273dc;
  font-size: 18px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
  transition: color 0.2s;
}

.icon-button:hover {
  color: #2366d1;
}

.icon-button i {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loader {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3273dc;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  display: inline-block;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.modal-card-body {
  max-height: calc(100vh - 200px);
  overflow-y: auto;
}
</style>
