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

const props = defineProps({
  params: Object
})

// Use the centralized role menu composable
const { getMenuType } = useRoleMenu()
const isFulCustomer = ref('Menu')

const shipment = ref({})
const isResubmitting = ref(false)

const getShipment = async () => {
  if(props.params.data.id) {
    const res = await $fetch(`/api/inouts/${props.params.data.id}/order`)
    if(res) {
      shipment.value = res
    }
  }
}
onMounted(() => {
  getShipment()
  isFulCustomer.value = getMenuType()
})
watch(() => props.params, getShipment)

// Show resubmit button when shipment has a tracking number and user is not a fulfillment customer
const canResubmit = computed(() => {
  return !!shipment.value?.TrackingNo && isFulCustomer.value !== 'c'
})

// Marketplace confirmation log: show info icon for non-limited roles.
// Colour it active when log data is present, grey otherwise — but always clickable.
const marketplaceConfirmLog = useMarketplaceConfirmLog()
const marketplaceConfirmLogParam = useMarketplaceConfirmLogParam()
const canShowConfirmLog = computed(() => isFulCustomer.value !== 'c' && !!shipment.value?.TrackingNo)
const hasConfirmLog = computed(() => {
  const v = shipment.value?.marketplace_confirm_log
  return !!(v && String(v).trim())
})
const openConfirmLog = () => {
  marketplaceConfirmLogParam.value = {
    documentNo: props.params.data?.documentNo || '',
    trackingNo: shipment.value?.TrackingNo || '',
    logBlob: shipment.value?.marketplace_confirm_log || '',
    fetchOrderId: props.params.data?.id
  }
  marketplaceConfirmLog.value = true
}

const resubmitConfirmation = async () => {
  if (!shipment.value?.id || isResubmitting.value) return

  isResubmitting.value = true
  try {
    const res = await $fetch('/api/commission/parcels/resubmit', {
      method: 'POST',
      body: {
        inoutId: shipment.value.id
      }
    })

    if (res?.status === 200) {
      toast({
        message: 'Shipment confirmation resubmitted successfully',
        type: 'is-success',
        duration: 3000,
        position: 'top-right'
      })
      // Refresh shipment data to update the button state
      await getShipment()
    } else {
      toast({
        message: res?.message || 'Failed to resubmit confirmation',
        type: 'is-danger',
        duration: 4000,
        position: 'top-right'
      })
    }
  } catch (err) {
    console.error('Failed to resubmit confirmation:', err)
    toast({
      message: 'Failed to resubmit shipment confirmation',
      type: 'is-danger',
      duration: 4000,
      position: 'top-right'
    })
  } finally {
    isResubmitting.value = false
  }
}

const copyTrackingNumber = async () => {
  if (!shipment.value?.TrackingNo) return

  try {
    await navigator.clipboard.writeText(shipment.value.TrackingNo)
    // Show success toast
    toast({
      message: `Tracking number copied: ${shipment.value.TrackingNo}`,
      type: 'is-success',
      duration: 2000,
      position: 'top-right'
    })
  } catch (err) {
    // Fallback for older browsers
    const textArea = document.createElement('textarea')
    textArea.value = shipment.value.TrackingNo
    textArea.style.position = 'fixed'
    textArea.style.left = '-999999px'
    document.body.appendChild(textArea)
    textArea.select()
    try {
      document.execCommand('copy')
      // Show success toast for fallback method
      toast({
        message: `Tracking number copied: ${shipment.value.TrackingNo}`,
        type: 'is-success',
        duration: 2000,
        position: 'top-right'
      })
    } catch (error) {
      console.error('Failed to copy tracking number:', error)
      // Show error toast
      toast({
        message: 'Failed to copy tracking number',
        type: 'is-danger',
        duration: 2000,
        position: 'top-right'
      })
    }
    document.body.removeChild(textArea)
  }
}

// Access M_ShipperCfg_ID.identifier from the shipment data via props.params.data.shipperCfgIdentifier
const getTrackingUrl = () => {
  if (!shipment.value?.TrackingNo) return null
  if (props.params.data.shipperCfgIdentifier === 'DHL') {
    return `https://www.dhl.de/de/privatkunden/pakete-empfangen/verfolgen.html?idc=${shipment.value.TrackingNo}`
  }
  return null
}
</script>

<template>
  <div class="tracking-container">
    <template v-if="shipment?.TrackingNo">
      <button
        v-if="canShowConfirmLog"
        @click="openConfirmLog"
        class="icon-button confirm-log-button"
        :class="{ 'has-log': hasConfirmLog }"
        :title="hasConfirmLog ? 'Show marketplace confirmation log' : 'Marketplace confirmation log (empty)'"
      >
        <i class="ti ti-list-details"></i>
      </button>
      <button
        v-if="canResubmit"
        @click="resubmitConfirmation"
        class="icon-button resubmit-button"
        :class="{ 'is-loading': isResubmitting }"
        :disabled="isResubmitting"
        title="Resubmit shipment confirmation to marketplace"
      >
        <i v-if="!isResubmitting" class="ti ti-refresh"></i>
        <i v-else class="ti ti-loader-2 spin"></i>
      </button>
      <a
        v-if="getTrackingUrl()"
        :href="getTrackingUrl()"
        target="_blank"
        class="tracking-number tracking-link"
        :title="'Open tracking: ' + shipment.TrackingNo"
      >
        {{ shipment.TrackingNo }}
      </a>
      <span
        v-else
        class="tracking-number"
        :title="shipment.TrackingNo"
      >
        {{ shipment.TrackingNo }}
      </span>
      <button
        @click="copyTrackingNumber"
        class="icon-button"
        title="Copy tracking number"
      >
        <i class="ti ti-copy"></i>
      </button>
    </template>
    <span v-else class="no-tracking" title="No tracking number">-</span>
  </div>
</template>

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

.tracking-number {
  font-size: 13px;
  font-weight: 500;
  color: #363636;
  white-space: nowrap;
  text-align: right;
}

.tracking-link {
  color: #3273dc;
  text-decoration: none;
  transition: color 0.2s;
  cursor: pointer;
}

.tracking-link:hover {
  color: #2366d1;
  text-decoration: underline;
}

.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;
  text-decoration: none;
  flex-shrink: 0;
}

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

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

.no-tracking {
  color: #999;
  font-size: 14px;
  text-align: right;
}

.resubmit-button {
  color: #ff9800;
}

.resubmit-button:hover {
  color: #f57c00;
}

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

.confirm-log-button {
  color: #9ca3af;
}
.confirm-log-button:hover {
  color: #6b7280;
}
.confirm-log-button.has-log {
  color: #1e3a8a;
}
.confirm-log-button.has-log:hover {
  color: #15287a;
}

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

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