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

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

const fetchFeeDetails = async () => {
  if (props.params.data.fulfillmentFeeTotal === 0) {
    return
  }

  isLoading.value = true
  showModal.value = true

  try {
    const res = await $fetch(`/api/fulfillment-fees?orderId=${props.params.data.id}`, {
      headers: useRequestHeaders(['cookie'])
    })
    console.log('Fulfillment fee details:', res)
    feeDetails.value = res
  } catch (error) {
    console.error('Failed to fetch fulfillment fee details:', error)
    feeDetails.value = { error: 'Failed to load data' }
  } finally {
    isLoading.value = false
  }
}

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

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

<template>
  <div class="fee-container">
    <span class="fee-bar" :class="props.params.data.feeEditable ? 'editable' : (props.params.data.fulfillmentFeeTotal > 0 ? 'not-editable' : 'no-fee')" :title="props.params.data.feeEditable ? 'Editable - fee lines not processed' : (props.params.data.fulfillmentFeeTotal > 0 ? 'Not editable - fee lines processed' : 'No fee lines')"></span>
    <span v-if="props.params.data.fulfillmentFeeTotal > 0" class="fee-value">
      {{ Number(props.params.data.fulfillmentFeeTotal).toLocaleString('de-DE', { style: 'currency', currency: props.params.data.currency || 'EUR' }) }}
    </span>
    <span class="icon-slot" style="margin-left: 4px;">
      <button
        v-if="props.params.data.feeProcessed"
        @click="fetchFeeDetails"
        style="border: none; padding: 0; margin: 0; width: 18px; height: 18px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; background-color: #ef4444; color: #fff; cursor: pointer; line-height: 1;"
        title="Fee processed - not editable"
      >
        <svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" viewBox="0 0 24 24" fill="#fff"><path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1v2z"/></svg>
      </button>
      <button
        v-else-if="props.params.data.fulfillmentFeeTotal > 0"
        @click="fetchFeeDetails"
        style="border: none; padding: 0; margin: 0; width: 18px; height: 18px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; background-color: #22c55e; color: #fff; cursor: pointer; font-size: 11px; font-weight: 700; font-style: italic; line-height: 1;"
        title="View fulfillment fee details"
      >i</button>
      <span v-else style="border: none; padding: 0; margin: 0; width: 18px; height: 18px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; background-color: #d1d5db; color: #fff; cursor: default; font-size: 11px; font-weight: 700; line-height: 1;" title="No fee lines">?</span>
    </span>
  </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">Fulfillment Fee Details - 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="feeDetails?.error" class="notification is-danger">
            {{ feeDetails.error }}
          </div>
          <div v-else-if="feeDetails?.records">
            <div class="mb-4">
              <strong>Total Records:</strong> {{ feeDetails['row-count'] }}
            </div>

            <div v-for="(record, index) in feeDetails.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>
                </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>
                </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>
                </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>
              </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: {{ feeDetails.records.reduce((sum, r) => sum + (r.LineTotalAmt || 0), 0).toLocaleString('de-DE', { style: 'currency', currency: props.params.data.currency || 'EUR' }) }}
                  </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(feeDetails, null, 2) }}</pre>
            </details>
          </div>
        </section>
        <footer class="modal-card-foot">
          <button class="button" @click="closeModal">Close</button>
        </footer>
      </div>
    </div>
  </Teleport>
</template>

<style scoped>
.fee-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 5px;
  height: 100%;
}

.fee-value {
  display: inline-flex;
  align-items: center;
}

.icon-slot {
  width: 18px;
  flex-shrink: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.icon-badge {
  border: none;
  padding: 0;
  margin: 0;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  line-height: 1;
  vertical-align: middle;
}

.lock-badge {
  border: none;
  padding: 0;
  margin: 0;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-color: #ef4444;
  color: #fff;
  cursor: pointer;
  line-height: 1;
}

.lock-badge:hover {
  background-color: #dc2626;
}

.icon-badge--fee {
  background-color: #22c55e;
  color: #fff;
  cursor: pointer;
}

.icon-badge--fee:hover {
  background-color: #16a34a;
}

.icon-badge--none {
  background-color: #d1d5db;
  color: #fff;
  cursor: default;
}

.icon-badge i {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 11px;
}

.icon-badge-letter {
  font-weight: 700;
  font-size: 12px;
  font-style: italic;
  line-height: 1;
  color: #fff;
}

.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;
}

.fee-bar {
  width: 4px;
  height: 100%;
  min-height: 20px;
  flex-shrink: 0;
  border-radius: 2px;
}

.fee-bar.editable {
  background-color: #22c55e;
}

.fee-bar.not-editable {
  background-color: #f59e0b;
}

.fee-bar.no-fee {
  background-color: #ef4444;
}
</style>
