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

const paymentReminder = usePaymentReminder()
const paymentReminderParam = usePaymentReminderParam()

const isOverdue = computed(() => {
  const data = props.params?.data
  if (!data) return false

  const isPaid = data.isPaid === true || data.isPaid === 'Y'
  const payAmt = data.payAmt || 0
  const grandTotal = data.grandTotal || 0

  // If paid, not overdue
  if (isPaid || (payAmt > 0 && payAmt >= grandTotal)) {
    return false
  }

  const netDays = data.netDays || 0
  const dateInvoiced = data.dateInvoiced

  if (dateInvoiced) {
    const invoiceDate = new Date(dateInvoiced)
    const dueDate = new Date(invoiceDate)
    dueDate.setDate(dueDate.getDate() + netDays)
    dueDate.setHours(0, 0, 0, 0)

    const today = new Date()
    today.setHours(0, 0, 0, 0)

    return today > dueDate
  }

  return false
})

const openReminderModal = () => {
  const data = props.params?.data
  if (!data) return

  paymentReminderParam.value = {
    id: data.id,
    documentNo: data.documentNo,
    partnerId: data.partnerId,
    partner: data.partner,
    grandTotal: data.grandTotal,
    currency: data.currency || 'EUR',
    dateInvoiced: data.dateInvoiced,
    netDays: data.netDays
  }
  paymentReminder.value = true
}
</script>

<template>
  <div v-if="params?.data" class="d-inlineFlex items-center justify-center">
    <span
      v-if="isOverdue"
      class="tf-icon ti ti-mail ti-sm fg-danger cursor-pointer reminder-btn"
      @click="openReminderModal"
      title="Send Payment Reminder"
    ></span>
    <span v-else class="no-action">-</span>
  </div>
</template>

<style scoped>
.reminder-btn:hover {
  opacity: 0.7;
}

.fg-danger {
  color: #dc3545;
}

.cursor-pointer {
  cursor: pointer;
}

.no-action {
  color: #999;
}
</style>
