<script setup>
import { date } from 'alga-js'
import { DatePicker } from 'tedir-calendar'
import { toast } from 'bulma-toast'

const quickPayment = useQuickPayment()
const quickPaymentParam = useQuickPaymentParam()

const form = ref({
  paymentDate: date.now('date'),
  payAmt: 0,
  processing: false
})

const closeModal = () => {
  quickPayment.value = false
  form.value = {
    paymentDate: date.now('date'),
    payAmt: 0,
    processing: false
  }
  quickPaymentParam.value = {}
}

watch(quickPayment, (newVal) => {
  if (newVal) {
    form.value.paymentDate = date.now('date')
    form.value.payAmt = quickPaymentParam.value.payAmt || 0
    form.value.processing = false
  }
})

const openFullPaymentWindow = () => {
  const data = quickPaymentParam.value
  const query = new URLSearchParams({
    invoiceId: data.invoiceId,
    invoice: data.invoice,
    partnerId: data.partnerId,
    partner: data.partner,
    payAmt: data.payAmt,
    currencyId: data.currencyId,
    currency: data.currency
  })
  closeModal()
  navigateTo(`/procurements/payments/create?${query.toString()}`)
}

const completePayment = async () => {
  if (!form.value.paymentDate || !form.value.payAmt) {
    toast({
      message: 'Please fill in payment date and amount',
      type: 'is-warning',
      duration: 2000
    })
    return
  }

  form.value.processing = true
  const data = quickPaymentParam.value

  try {
    // Step 1: Create the payment
    const createRes = await $fetch('/api/payments/store', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: data.organizationId,
        isActive: true,
        documentNo: '',
        description: '',
        isApproved: false,
        processed: false,
        creditCardNumber: 0,
        creditCardExpMM: Number(new Date().getMonth()) + 1,
        creditCardExpYY: new Date().getFullYear(),
        isReconciled: false,
        taxAmt: 0,
        discountAmt: 0,
        payAmt: (data.docBaseType === 'ARC' || data.docBaseType === 'APC') ? -Math.abs(form.value.payAmt) : form.value.payAmt,
        dateTrx: form.value.paymentDate,
        isAllocated: false,
        isOnline: false,
        isReceipt: data.docBaseType !== 'ARC' && data.docBaseType !== 'APC',
        writeOffAmt: 0,
        overUnderAmt: 0,
        isOverUnderPayment: false,
        isSelfService: false,
        isDelayedCapture: false,
        chargeAmt: 0,
        R_CVV2Match: 0,
        dateAcct: form.value.paymentDate,
        isPrepayment: false,
        processedOn: 0,
        isVoided: false,
        isOverrideCurrencyRate: false,
        routingNo: '',
        accountNo: '',
        A_Zip: '',
        A_Ident_DL: '',
        A_Ident_SSN: '',
        A_EMail: '',
        voiceAuthCode: '',
        orig_TrxID: '',
        micr: '',
        checkNo: '',
        A_Name: '',
        A_Street: '',
        A_City: '',
        A_State: '',
        A_Country: '',
        swiftCode: '',
        creditCardTypeId: '',
        bankAccountId: '1000000',
        trxTypeId: '',
        tenderTypeId: 'A',
        currencyId: data.currencyId,
        docTypeId: data.docBaseType === 'APC' ? '1000009' : '1000008',
        orderId: '',
        invoiceId: data.invoiceId,
        docStatusId: 'DR',
        partnerId: data.partnerId,
        chargeId: '',
        projectId: '',
        campaignId: '',
      }
    })

    if (Number(createRes.status) !== 200 || !Number(createRes.id)) {
      toast({
        message: createRes.message || 'Failed to create payment',
        type: 'is-danger',
        duration: 3000
      })
      form.value.processing = false
      return
    }

    // Step 2: Complete the payment (document action CO)
    const completeRes = await $fetch(`/api/payments/${createRes.id}/document-action`, {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        documentAction: 'CO'
      }
    })

    if (Number(completeRes.status) >= 400) {
      toast({
        message: completeRes.message || 'Payment created but failed to complete. Check the payment manually.',
        type: 'is-warning',
        duration: 5000
      })
    } else {
      toast({
        message: `Payment completed for ${data.invoice}`,
        type: 'is-success',
        duration: 3000
      })
    }

    // Step 3: Refresh the AG Grid
    if (quickPaymentParam.value.refreshCallback) {
      quickPaymentParam.value.refreshCallback()
    }

    closeModal()
  } catch (err) {
    console.error('Quick payment error:', err)
    toast({
      message: 'Failed to process payment',
      type: 'is-danger',
      duration: 3000
    })
    form.value.processing = false
  }
}
</script>

<template>
  <div class="email-modal-overlay" v-if="quickPayment" @click.self="closeModal">
    <div class="email-modal-container" @click.stop>
      <div class="email-modal-header">
        <h3 class="email-modal-title">Quick Payment</h3>
        <div class="cursor-pointer" @click="closeModal">
          <span class="tf-icon ti ti-x ti-sm"></span>
        </div>
      </div>
      <div class="email-modal-body">
        <div class="mb-3">
          <div class="d-flex justify-between items-center">
            <span class="form-label-inline"><strong>Invoice:</strong> {{ quickPaymentParam.invoice }}</span>
            <span class="form-label-inline"><strong>Partner:</strong> {{ quickPaymentParam.partner }}</span>
          </div>
        </div>
        <div class="mb-3">
          <label class="form-label">Payment Date *</label>
          <DatePicker v-model="form.paymentDate" locale="de-DE" :option="{ day: '2-digit', month: '2-digit', year: 'numeric' }" />
        </div>
        <div class="mb-3">
          <label class="form-label">Amount *</label>
          <input
            type="number"
            step="0.01"
            v-model="form.payAmt"
            class="form-control"
            placeholder="Payment amount"
          />
        </div>
        <div class="mb-3">
          <small class="text-muted">
            Bank Account: Volksbank Mittelhessen | Tender: Direct Deposit | Doc Type: {{ quickPaymentParam.docBaseType === 'APC' ? 'AP Payment' : quickPaymentParam.docBaseType === 'ARC' ? 'AR Credit Memo' : 'AR Receipt' }}
          </small>
        </div>
      </div>
      <div class="email-modal-footer">
        <button type="button" class="button" @click="openFullPaymentWindow" :disabled="form.processing" title="Open full payment window">
          <span class="tf-icon ti ti-external-link ti-xs me-1 color-inherit"></span> Open
        </button>
        <div class="d-flex gap-10px">
          <button type="button" class="button" @click="closeModal" :disabled="form.processing">Cancel</button>
          <button
            type="button"
            class="button button-success"
            @click="completePayment"
            :class="{'pointerEvents-none opacity-0.6': form.processing || !form.paymentDate || !form.payAmt}"
            :disabled="form.processing || !form.paymentDate || !form.payAmt"
          >
            <span v-if="form.processing">Processing...</span>
            <span v-else>
              <span class="tf-icon ti ti-check ti-xs me-1 color-inherit"></span> Complete Payment
            </span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.email-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
}
.email-modal-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  width: 100%;
  max-width: 450px;
  max-height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}
.email-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
}
.email-modal-title {
  margin: 0;
  font-size: 1.1rem;
  font-weight: 600;
}
.email-modal-body {
  padding: 20px;
  flex: 1;
  overflow: visible;
  min-height: 350px;
}
.email-modal-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
  padding: 16px 20px;
  border-top: 1px solid #eee;
}
.form-label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}
.form-label-inline {
  font-size: 0.875rem;
}
.form-control {
  width: 100%;
  padding: 0.5rem 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.875rem;
  box-sizing: border-box;
}
.form-control:focus {
  outline: none;
  border-color: #666;
}
.text-muted {
  color: #6c757d;
}
.button-success {
  background-color: #28a745;
  color: white;
  border-color: #28a745;
}
.button-success:hover {
  background-color: #218838;
}
.mb-3 {
  margin-bottom: 1rem;
}
.cursor-pointer {
  cursor: pointer;
}
</style>
