<script setup>
import { date, string } from 'alga-js'
import { toast } from 'bulma-toast'

const router = useRouter()
const tabs = useTabs()
const printPreview = usePrintPreview()
const printParam = usePrintParam()
const quickView = useQuickView()
const quickViewParam = useQuickViewParam()
const generateShipments = useGenerateShipments()
const generateShipmentActive = useGenerateShipmentActive()
const generateInvoices = useGenerateInvoices()
const generateInvoiceActive = useGenerateInvoiceActive()
const { t } = useTranslation()

const props = defineProps({
  params: Object
})

// Use the centralized role menu composable
const { getMenuType } = useRoleMenu()

// Use a computed property that will be reactive
const isFulCustomer = computed(() => getMenuType())

// Void / "Stornieren" confirmation modal — the native confirm() dialog didn't
// make clear enough that the action is permanent (not a hold), so the flow
// now routes through an explicit modal with a warning block.
const showVoidModal = ref(false)
const voidPending = ref(false)

const openVoidModal = () => { showVoidModal.value = true }
const closeVoidModal = () => { if (!voidPending.value) showVoidModal.value = false }

const confirmVoid = async () => {
  if (!props.params.data?.id || voidPending.value) return
  voidPending.value = true
  try {
    const res = await $fetch('/api/orders/' + props.params.data.id + '/document-action', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: { documentAction: 'VO' }
    })
    if (res) {
      toast({ message: t.value.order_void_success || 'Order cancelled', type: 'is-success', duration: 2000 })
      showVoidModal.value = false
      location.reload()
    } else {
      toast({ message: t.value.order_void_error || 'Failed to cancel order', type: 'is-danger', duration: 2500 })
    }
  } catch (err) {
    toast({ message: (err?.message || t.value.order_void_error || 'Failed to cancel order'), type: 'is-danger', duration: 2500 })
  } finally {
    voidPending.value = false
  }
}

const removeQueryFromPath = (path) => {
  let newPath = path
  if(path.includes('?')) {
    const splittedPath = path.split('?')
    newPath = splittedPath[0]
  }
  return newPath
}

const openTab = (toPath, pathName, oldPath = null) => {
  let comparePath = toPath
  if(oldPath) {
    comparePath = oldPath
  }
  tabs.value.map(item => {
    item.active = false
    return item
  })
  if(tabs.value.filter(i => i.link === removeQueryFromPath(comparePath)).length >= 1) {
    const tabIndex = tabs.value.findIndex(i => i.link === removeQueryFromPath(comparePath))
    tabs.value[tabIndex].active = true
    if(oldPath) {
      tabs.value[tabIndex].link = removeQueryFromPath(toPath)
      tabs.value[tabIndex].text = pathName
    }
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  } else {
    tabs.value.push({link: removeQueryFromPath(toPath), text: pathName, active: true})
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  }
  //location.href = toPath
}

const viewHandler = () => {
  //router.push(`/sales/orders/${props.params.data.id}/view`)
  //replaceActiveTabUrl(`/sales/orders/${props.params.data.id}/view`)
  quickView.value = 'order'
  quickViewParam.value = props.params.data
}
const duplicateHandler = () => {
  //router.push(`/sales/orders/${props.params.data.id}/duplicate`)
  openTab(`/duplicate/sales-order-${props.params.data.id}`, `Sales Order: Duplicate`)
}
const printHandler = () => {
  //router.push(`/sales/orders/${props.params.data.id}/print`)
  printParam.value = props.params.data
  printPreview.value = true
}
const generateShipmentHandler = async () => {
  generateShipments.value = {
    warehouse: props.params.data.warehouse,
    warehouseId: props.params.data.warehouseId,
    partner: props.params.data.partner,
    partnerId: props.params.data.partnerId
  }
  generateShipmentActive.value = true
  /*openTab('/generate-shipments', 'Generate Shipments')*/

  /*const res = await $fetch('/api/processes/inouts/generate', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      warehouseId: props.params.data.warehouseId,
      dateAcct: date.now('date'),
      partnerId: props.params.data.partnerId,
      datePromised: date.now('date'),
      docStatusId: 'CO',
      isUnconfirmed: false,
      isOneDocument: false,
      inProgress: false,
      isRunJob: false,
    }
  })

  if(Number(res.status) === 200) {
    toast({
      message: `Shipment has been generated from sales order`,
      type: 'is-success',
      duration: 2000
    })
  }*/
}
const generateInvoiceHandler = async () => {
  generateInvoices.value = {
    partner: props.params.data.partner,
    partnerId: props.params.data.partnerId,
    order: props.params.data.documentNo,
    orderId: props.params.data.id
  }
  generateInvoiceActive.value = true
  openTab('/generate-invoices', 'Generate Invoices')
}
const editHandler = () => {
  //router.push(`/sales/orders/${props.params.data.id}/edit`)
  openTab(`/edit/sales-order-${props.params.data.id}`, `Sales Order: ${props.params.data.documentNo}`)
}
const deleteHandler = async () => {
  const confirmation = confirm('Are you sure want to delete this record?')
  if(confirmation) {
    const res = await $fetch('/api/orders/'+props.params.data.id, {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })

    if(res) {
      // Remove the row from ag-grid instead of reloading
      props.params.api.applyTransaction({ remove: [props.params.data] })

      toast({
        message: 'Order deleted successfully',
        type: 'is-success',
        duration: 2000
      })
    } else {
      toast({
        message: 'Failed to delete order',
        type: 'is-danger',
        duration: 2000
      })
    }
  }
}

const checkNumberInStreet = computed(() => {
  let numStreet = true
  if(props.params.data?.locationStreet) {
    const match = props.params.data.locationStreet.match(/(\d+[a-zA-Z]*.*)$/)
    numStreet = match ? true : false
  }
  return numStreet
})

const shipment = ref({})
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)
watch(() => props.params, getShipment)

 // console.log(props.params.data)
</script>

<template>
  <div class="d-inlineFlex items-center gap-5px">
<!--    <span class="tf-icon ti ti-eye ti-sm me-1 fg-info cursor-pointer" @click="viewHandler" title="View"></span>-->
    <span class="tf-icon ti ti-file-invoice ti-sm me-1 fg-primary cursor-pointer" @click="printHandler" title="Print"></span>
<!--    <span class="tf-icon ti ti-copy ti-sm me-1 fg-info cursor-pointer" @click="duplicateHandler" title="Duplicate"></span>-->
<!--    <span>{{props.params.data?.minout?.TrackingNo}}</span>-->
    <span v-if="params?.data?.docStatusId !== 'CO' && params?.data?.docStatusId !== 'VO'" class="tf-icon ti ti-pencil ti-sm me-1 fg-warning cursor-pointer" @click="editHandler" title="Edit"></span>
<!--    <span v-else class="tf-icon ti ti-forms ti-sm me-1 fg-warning cursor-pointer" @click="editHandler" title="Open"></span>-->
<!--    <span v-if="params.data.docStatusId === 'CO' && checkNumberInStreet && !props.params.data?.minout[0]?.TrackingNo" class="tf-icon ti ti-truck ti-sm me-1 fg-primary cursor-pointer" @click="generateShipmentHandler" title="Generate Shipments"></span>-->
    <span v-if="isFulCustomer !== 'c' && !shipment?.TrackingNo" class="tf-icon ti ti-truck ti-sm me-1 fg-primary cursor-pointer" @click="generateShipmentHandler" title="Generate Shipments"></span>
    <span v-if="isFulCustomer !== 'c' && params?.data?.docStatusId === 'CO'" class="tf-icon ti ti-currency-dollar ti-sm me-1 fg-success cursor-pointer" @click="generateInvoiceHandler" title="Generate Invoice"></span>
    <span v-if="params?.data?.docStatusId !== 'CO' && params?.data?.docStatusId !== 'VO'" class="tf-icon ti ti-trash ti-sm me-1 fg-danger cursor-pointer" @click="deleteHandler" title="Delete"></span>
<!--    <span>{{ params.data.documentNo }}</span>-->
    <span v-if="params?.data?.docStatusId !== 'VO' && !shipment?.TrackingNo" class="tf-icon ti ti-file-x ti-sm me-1 fg-danger cursor-pointer" @click="openVoidModal" :title="t.order_void_action"></span>

    <!-- Cancel-order confirmation modal -->
    <Teleport to="body">
      <div v-if="showVoidModal" class="void-modal" @click.self="closeVoidModal">
        <div class="void-modal-card" @click.stop>
          <header class="void-modal-head">
            <span class="ti ti-file-x void-modal-icon"></span>
            <h3 class="void-modal-title">{{ t.order_void_title }}</h3>
          </header>
          <section class="void-modal-body">
            <div class="void-modal-doc" v-if="params?.data?.documentNo">#{{ params.data.documentNo }}</div>
            <div class="void-modal-warning">
              <span class="ti ti-alert-triangle void-modal-warning-icon"></span>
              <span>{{ t.order_void_warning }}</span>
            </div>
          </section>
          <footer class="void-modal-foot">
            <button type="button" class="void-btn" @click="closeVoidModal" :disabled="voidPending">
              {{ t.order_void_keep || t.cancel }}
            </button>
            <button type="button" class="void-btn void-btn--danger" @click="confirmVoid" :disabled="voidPending">
              <span v-if="voidPending" class="ti ti-loader-2 spin"></span>
              <span v-else class="ti ti-file-x"></span>
              {{ t.order_void_confirm }}
            </button>
          </footer>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<style scoped>
.void-modal { position: fixed; inset: 0; background: rgba(17, 24, 39, 0.55); display: flex; align-items: center; justify-content: center; z-index: 9999; padding: 1rem; }
.void-modal-card { width: 100%; max-width: 460px; background: var(--theme-bg-primary, #fff); border-radius: 12px; overflow: hidden; box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3); }
.void-modal-head { display: flex; align-items: center; gap: 0.75rem; padding: 1rem 1.25rem; border-bottom: 1px solid var(--theme-border, #e5e7eb); background: #fee2e2; }
.void-modal-icon { font-size: 1.5rem; color: #dc2626; }
.void-modal-title { margin: 0; font-size: 1.125rem; font-weight: 700; color: #7f1d1d; }
.void-modal-body { padding: 1.25rem; }
.void-modal-doc { font-size: 0.8125rem; font-weight: 700; color: var(--theme-text-secondary, #6b7280); margin-bottom: 0.75rem; letter-spacing: 0.03em; }
.void-modal-warning { display: flex; gap: 0.625rem; padding: 0.875rem 1rem; background: #fef3c7; border: 1px solid #fcd34d; border-left: 4px solid #f59e0b; border-radius: 8px; color: #92400e; font-size: 0.875rem; line-height: 1.5; }
.void-modal-warning-icon { font-size: 1.25rem; flex-shrink: 0; color: #b45309; }
.void-modal-foot { display: flex; gap: 0.5rem; justify-content: flex-end; padding: 0.875rem 1.25rem; border-top: 1px solid var(--theme-border, #e5e7eb); background: var(--theme-bg-secondary, #fafafa); }
.void-btn { display: inline-flex; align-items: center; gap: 0.375rem; padding: 0.5rem 1rem; border: 1.5px solid var(--theme-border, #d1d5db); border-radius: 8px; background: var(--theme-bg-primary, #fff); color: var(--theme-text-primary, #1f2937); font-size: 0.875rem; font-weight: 600; cursor: pointer; transition: all 0.15s; }
.void-btn:hover:not(:disabled) { background: #f3f4f6; }
.void-btn:disabled { opacity: 0.5; cursor: not-allowed; }
.void-btn--danger { background: #dc2626; border-color: #dc2626; color: #fff; }
.void-btn--danger:hover:not(:disabled) { background: #b91c1c; border-color: #b91c1c; }
.spin { animation: void-spin 1s linear infinite; }
@keyframes void-spin { to { transform: rotate(360deg); } }
[data-mode="dark"] .void-modal-card { background: #1f2937; }
[data-mode="dark"] .void-modal-head { background: #3f1d1d; }
[data-mode="dark"] .void-modal-title { color: #fecaca; }
[data-mode="dark"] .void-modal-foot { background: #111827; border-top-color: #374151; }
[data-mode="dark"] .void-btn { background: #1f2937; border-color: #374151; color: #f3f4f6; }
[data-mode="dark"] .void-btn:hover:not(:disabled) { background: #374151; }
[data-mode="dark"] .void-modal-warning { background: #3b2506; border-color: #92400e; color: #fbbf24; }
</style>