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

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

export default {
	name: 'BuyPrepaidCreditsPayPal',
	props: {
		amount: {
			default: 0
		},
		minimumAmount: {
			default: 0
		},
		isOnboarding: {
			default: false
		}
	},
	emits: ['success', 'cancel'],
	data() {
		return {
			loading: false,
			error: null
		};
	},
	resources: {
		createPayPalOrder() {
			return {
				url: 'jcloud.api.billing.create_paypal_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'));
					
					// Check payment status periodically
					this.checkPaymentStatus(response.order_id);
				}
			};
		}
	},
	methods: {
		processPayPalPayment() {
			this.$resources.createPayPalOrder.submit();
		},
		
		// Optional: method to check payment status
		checkPaymentStatus(orderId) {
			const checkInterval = setInterval(() => {
				this.$call('jcloud.api.billing.check_payment_status', {
					order_id: orderId,
					payment_type: 'paypal'
				}).then(result => {
					if (result && result.status === 'Success') {
						clearInterval(checkInterval);
						toast.success(this.$t('Payment successful! Account has been recharged'));
						this.$emit('success');
					}
				}).catch(err => {
					console.error('Error checking payment status:', err);
				});
			}, 3000);
			
			// Stop checking after 5 minutes
			setTimeout(() => {
				clearInterval(checkInterval);
			}, 300000);
		}
	}
};
</script>

<style scoped>
.paypal-btn {
	background-color: #00457C;
	color: white;
}

.paypal-btn:hover {
	background-color: #003057;
}
</style>