<template>
	<div class="billing-invoices-container">
		<ObjectList :options="options" />
		<Dialog
			v-model="invoiceDialog"
			:options="{ size: '3xl', title: showInvoice?.name }"
		>
			<template #body-content>
				<template v-if="showInvoice">
					<div
						v-if="showInvoice.status === 'Empty'"
						class="text-base text-gray-600"
					>
						{{ $t('No content to display') }}
					</div>
					<InvoiceTable v-else :invoiceId="showInvoice.name" />
				</template>
			</template>
		</Dialog>
		<AddPrepaidCreditsDialog
			v-if="showBuyPrepaidCreditsDialog"
			v-model="showBuyPrepaidCreditsDialog"
			:minimumAmount="minimumAmount"
			@success="
				() => {
					showBuyPrepaidCreditsDialog = false;
				}
			"
		/>
	</div>
</template>
<script>
import { h } from 'vue';
import { Button } from 'jingrow-ui';
import ObjectList from '../components/ObjectList.vue';
import InvoiceTable from '../components/InvoiceTable.vue';
import { userCurrency, date } from '../utils/format';
import { confirmDialog, icon, renderInDialog } from '../utils/components';
import AddPrepaidCreditsDialog from '../components/billing/AddPrepaidCreditsDialog.vue';
import { dayjsLocal } from '../utils/dayjs';
import router from '../router';

export default {
	name: 'BillingInvoices',
	props: ['tab'],
	components: {
		ObjectList,
		InvoiceTable,
		AddPrepaidCreditsDialog,
	},
	data() {
		return {
			invoiceDialog: false,
			showInvoice: null,
			showBuyPrepaidCreditsDialog: false,
			minimumAmount: 0,
		};
	},
	computed: {
		options() {
			return {
				pagetype: 'Invoice',
				fields: [
					'type',
					'invoice_pdf',
					'payment_mode',
					'stripe_invoice_url',
					'due_date',
					'period_start',
					'period_end',
					'mpesa_invoice',
					'mpesa_invoice_pdf',
				],
				filterControls: () => {
					return [
						{
							type: 'select',
							label: this.$t('Type'),
							class: !this.$isMobile ? 'w-36' : '',
							fieldname: 'type',
							options: [
								{ label: '', value: '' },
								{ label: this.$t('Subscription'), value: 'Subscription' },
								{ label: this.$t('Prepaid Credits'), value: 'Prepaid Credits' },
							],
						},
						{
							type: 'select',
							label: this.$t('Status'),
							class: !this.$isMobile ? 'w-36' : '',
							fieldname: 'status',
							options: [
								{ label: '', value: '' },
								{ label: this.$t('Draft'), value: 'Draft' },
								{ label: this.$t('Invoice Created'), value: 'Invoice Created' },
								{ label: this.$t('Unpaid'), value: 'Unpaid' },
								{ label: this.$t('Paid'), value: 'Paid' },
								{ label: this.$t('Refunded'), value: 'Refunded' },
								{ label: this.$t('Uncollectible'), value: 'Uncollectible' },
								{ label: this.$t('Collected'), value: 'Collected' },
								{ label: this.$t('Empty'), value: 'Empty' },
							],
						},
					];
				},
				columns: [
					{
						label: this.$t('Invoice'),
						fieldname: 'name',
						class: 'font-medium',
						format(value, row) {
							if (row.type == 'Subscription') {
								let end = dayjsLocal(row.period_end);
                                // Format as YYYY-MM
                                return end.format('YYYY-MM'); 
                            } else if (row.type == 'Partnership Fees') {
                                return 'Partnership Fees';
                            }
                            return 'Prepaid Credits';
						},
						width: 0.8,
					},
					{
						label: this.$t('Status'),
						fieldname: 'status',
						type: 'Badge',
						width: '150px',
					},
					{
						label: this.$t('Date'),
						fieldname: 'due_date',
						format(value, row) {
							if (row.type == 'Subscription') {
								let start = dayjsLocal(row.period_start);
								let end = dayjsLocal(row.period_end);
                                // Format as YYYY-MM-DD
                                return `${start.format('YYYY-MM-DD')} - ${end.format('YYYY-MM-DD')}`; 
                            }
                            // Format as YYYY-MM-DD
                            return dayjsLocal(value).format('YYYY-MM-DD'); 
						},
					},
					{
						label: this.$t('Total'),
						fieldname: 'total',
						format: this.formatCurrency,
						align: 'right',
						width: 0.6,
					},
					{
						label: this.$t('Amount Paid'),
						fieldname: 'amount_paid',
						format: this.formatCurrency,
						align: 'right',
						width: 0.6,
					},
					{
						label: this.$t('Amount Due'),
						fieldname: 'amount_due',
						format: this.formatCurrency,
						align: 'right',
						width: 0.6,
					},
					{
						label: '',
						type: 'Button',
						align: 'right',
						Button: ({ row }) => {
							if (row.invoice_pdf || row.mpesa_invoice_pdf) {
								return {
									label: this.$t('Download Invoice'),
									slots: {
										prefix: icon('download'),
									},
									onClick: () => {
										if (row.mpesa_invoice_pdf) {
											window.open(row.mpesa_invoice_pdf);
										} else {
											window.open(row.invoice_pdf);
										}
									},
								};
							}
							if (row.status === 'Unpaid' && row.amount_due > 0) {
								return {
									label: this.$t('Pay Now'),
									slots: {
										prefix: icon('external-link'),
									},
									onClick: (e) => {
										e.stopPropagation();
										if (row.stripe_invoice_url && row.payment_mode == 'Card') {
											window.open(
												`/api/action/jcloud.api.client.run_pg_method?dt=Invoice&dn=${row.name}&method=stripe_payment_url`,
											);
										} else {
											this.showBuyPrepaidCreditsDialog = true;
											this.minimumAmount = row.amount_due;
										}
									},
								};
							}
						},
						prefix(row) {
							if (row.stripe_payment_failed && row.status !== 'Paid') {
								return h(Button, {
									variant: 'ghost',
									theme: 'red',
									icon: 'alert-circle',
									onClick(e) {
										e.stopPropagation();
										confirmDialog({
											title: this.$t('Payment Failed'),
											message: `<div class="space-y-4"><p class="text-base">${this.$t('Payment for this invoice failed using card ending in')} <strong>${row.stripe_payment_failed_card}</strong>. ${this.$t('Reason:')}</p><div class="text-sm font-mono text-gray-600 rounded p-2 bg-gray-100">${row.stripe_payment_error}</div><p class="text-base">${this.$t('Please update your payment method to pay this invoice.')}</p></div>`,
											primaryAction: {
												label: this.$t('Update Payment Method'),
												variant: 'solid',
												onClick: ({ hide }) => {
													hide();
													router.push({
														name: 'BillingPaymentMethods',
													});
												},
											},
										});
									},
								});
							}
						},
					},
				],
				orderBy: 'due_date desc, creation desc',
				onRowClick: (row) => {
					this.showInvoice = row;
					this.invoiceDialog = true;
				},
			};
		},
	},
	methods: {
		formatCurrency(value) {
			if (value === 0) {
				return '';
			}
			return userCurrency(value);
		},
	},
};
</script>

<style scoped>
.billing-invoices-container {
	padding: 24px;
	width: 100%;
}

@media (max-width: 768px) {
	.billing-invoices-container {
		padding: 16px;
	}
}
</style>