<template>
	<div>
		<span
			v-if="team.pg.currency === 'CNY'"
			class="mt-2.5 inline-flex gap-2 text-base text-gray-700"
		>
			<FeatherIcon name="info" class="my-1 h-4" />
			<span class="leading-5">
				如果您选择 Razorpay，您可以使用信用卡、借记卡、网上银行、UPI、钱包等方式支付。如果您使用网上银行，余额可能需要最多5天才能到账。
			</span>
		</span>
		<ErrorMessage class="mt-3" :message="createRazorpayOrder.error" />
		<div class="mt-8">
			<Button
				v-if="!isPaymentComplete"
				class="w-full"
				size="md"
				variant="solid"
				label="继续使用 Razorpay 支付"
				:loading="createRazorpayOrder.loading"
				@click="createRazorpayOrder.submit()"
			/>
			<Button
				v-else
				class="w-full"
				size="md"
				label="确认支付中"
				variant="solid"
				:loading="isVerifyingPayment"
			/>
		</div>
	</div>
</template>
<script setup>
import { Button, ErrorMessage, FeatherIcon, createResource } from 'jingrow-ui';
import { ref, onMounted, onBeforeUnmount, inject } from 'vue';
import { toast } from 'vue-sonner';
import { DashboardError } from '../../utils/error';

const props = defineProps({
	amount: {
		type: Number,
		default: 0
	},
	maximumAmount: {
		type: Number,
		default: 0
	},
	type: {
		type: String,
		default: 'prepaid-credits'
	}
});

const emit = defineEmits(['success']);
const team = inject('team');

const isPaymentComplete = ref(false);
const isVerifyingPayment = ref(false);

const razorpayCheckoutJS = ref(null);

onMounted(() => {
	razorpayCheckoutJS.value = document.createElement('script');
	razorpayCheckoutJS.value.setAttribute(
		'src',
		'https://checkout.razorpay.com/v1/checkout.js'
	);
	razorpayCheckoutJS.value.async = true;
	document.head.appendChild(razorpayCheckoutJS.value);
});

onBeforeUnmount(() => {
	razorpayCheckoutJS.value?.remove();
});

let order_type =
	props.type === 'prepaid-credits' ? 'Prepaid Credits' : 'Partnership Fee';

const createRazorpayOrder = createResource({
	url: 'jcloud.api.billing.create_razorpay_order',
	params: {
		amount: props.amount,
		type: order_type
	},
	onSuccess: data => processOrder(data),
	validate: () => {
		if (props.amount > props.maximumAmount) {
			throw new DashboardError('Amount more than maximum amount required');
		}
	}
});

const handlePaymentFailed = createResource({
	url: 'jcloud.api.billing.handle_razorpay_payment_failed',
	onSuccess: () => {
		console.log('Payment Failed.');
	}
});

function processOrder(data) {
	const options = {
		key: data.key_id,
		order_id: data.order_id,
		name: 'Jingrow',
		image: 'https://jingrow.com/files/cloud.png',
		prefill: { email: team.pg?.user },
		handler: handlePaymentSuccess,
		theme: { color: '#171717' }
	};

	const rzp = new Razorpay(options);

	// Opens the payment checkout frame
	rzp.open();

	// Attach failure handler
	rzp.on('payment.failed', handlePaymentFailure);
	// rzp.on('payment.success', this.handlePaymentSuccess);
}

function handlePaymentFailure(response) {
	handlePaymentFailed.submit({ response });
	toast.error('支付失败');
}

function handlePaymentSuccess() {
	isPaymentComplete.value = true;
	emit('success');
	toast.success('支付成功');
}
</script>