<template>
	<div>
		<ErrorMessage
			class="mt-3"
			:message="$resources.createAlipayOrder.error || error"
		/>
		<div class="mt-4 flex w-full justify-end">
			<Button
				variant="solid"
				class="alipay-btn"
				:loading="$resources.createAlipayOrder.loading || loading"
				@click="processAlipayPayment"
			>
				{{ $t('Pay with Alipay') }}
			</Button>
		</div>
	</div>
</template>

<script>
import { toast } from 'vue-sonner';
import { DashboardError } from '../utils/error';

export default {
	name: 'BuyPrepaidCreditsAlipay',
	props: {
		amount: {
			default: 0
		},
		minimumAmount: {
			default: 0
		},
		isOnboarding: {
			default: false
		}
	},
	data() {
		return {
			loading: false,
			error: null
		};
	},
	resources: {
		createAlipayOrder() {
			return {
				url: 'jcloud.api.billing.create_alipay_order_for_recharge',
				params: {
					amount: this.amount
				},
				validate() {
					if (this.amount <= 0) {
						throw new DashboardError(this.$t('Payment amount must be greater than 0'));
					}
					if (this.amount < this.minimumAmount) {
						throw new DashboardError(this.$t('Amount is below the minimum required amount'));
					}
				},
				onSuccess(response) {
					window.open(response.payment_url, '_blank');
					
					toast.success(this.$t('Payment page opened in new window'));
					
					// Optional: check payment status
					// this.checkPaymentStatus(response.order_id);
				}
			};
		}
	},
	methods: {
		processAlipayPayment() {
			this.$resources.createAlipayOrder.submit().catch(err => {
				// Prevent "Uncaught (in promise)" error in console
				// The error is already displayed in the UI via the ErrorMessage component
			});
		},
		
		// Optional: method to check payment status
		checkPaymentStatus(orderId) {
			const checkInterval = setInterval(() => {
				this.$call('jcloud.api.billing.check_payment_status', {
					order_id: orderId,
					payment_type: 'alipay'
				}).then(result => {
					if (result && result.status === 'Success') {
						clearInterval(checkInterval);
						toast.success(this.$t('Payment successful! Account has been recharged'));
						this.$emit('payment-success');
					}
				}).catch(err => {
					// Error checking payment status
				});
			}, 3000);
			
			// Stop checking after 5 minutes
			setTimeout(() => {
				clearInterval(checkInterval);
			}, 300000);
		}
	}
};
</script>

<style scoped>
.alipay-btn {
	background-color: #1677FF !important;
	border: none;
	color: white;
	border-radius: 4px;
	font-size: 1rem;
	padding: 0.625rem 1.25rem;
	transition: all 0.2s ease;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.alipay-btn:hover {
	background-color: #0e66e7 !important;
	transform: translateY(-1px);
	box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
}
</style> 