<template>
	<n-space vertical :size="24">
		<n-card class="payment-details-card" :title="$t('Account Balance')">
			<n-space vertical :size="16">
				<div class="balance-section">
					<div class="balance-info">
						<div class="balance-amount">
							{{ availableCredits || currency + ' 0.00' }}
						</div>
					</div>
					<n-button
						type="primary"
						@click="
							() => {
								showMessage = false;
								showAddPrepaidCreditsDialog = true;
							}
						"
						:size="buttonSize"
						:block="isMobile"
					>
						<template #icon>
							<i-lucide-plus class="h-4 w-4" />
						</template>
						{{ $t('Recharge') }}
					</n-button>
				</div>
			</n-space>
		</n-card>

		<n-card class="payment-details-card" :title="$t('Billing Address')">
			<n-space vertical :size="16">
				<div class="address-section">
					<div class="address-info">
						<div v-if="billingDetailsSummary" class="address-text">
							{{ billingDetailsSummary }}
						</div>
						<div v-else class="address-empty">
							{{ $t('No address') }}
						</div>
					</div>
					<n-button
						:type="billingDetailsSummary ? 'default' : 'primary'"
						@click="
							() => {
								showMessage = false;
								showBillingDetailsDialog = true;
							}
						"
						:size="buttonSize"
						:block="isMobile"
					>
						<template v-if="!billingDetailsSummary" #icon>
							<i-lucide-plus class="h-4 w-4" />
						</template>
						{{ billingAddressButtonLabel }}
					</n-button>
				</div>
			</n-space>
		</n-card>
	</n-space>

	<BillingDetailsDialog
		v-if="showBillingDetailsDialog"
		v-model="showBillingDetailsDialog"
		:showMessage="showMessage"
		@success="billingDetails.reload()"
	/>
	<AddPrepaidCreditsDialog
		v-if="showAddPrepaidCreditsDialog"
		v-model="showAddPrepaidCreditsDialog"
		:showMessage="showMessage"
		@success="upcomingInvoice.reload()"
	/>
</template>
<script setup>
import { NCard, NSpace, NButton } from 'naive-ui';
import BillingDetailsDialog from './BillingDetailsDialog.vue';
import AddPrepaidCreditsDialog from './AddPrepaidCreditsDialog.vue';
import { createResource } from 'jingrow-ui';
import { computed, ref, inject, onMounted, onUnmounted, nextTick, getCurrentInstance } from 'vue';

// 英文国家名到中文的映射
const countryToZh = {
	'China': '中国',
	'United States': '美国',
	// 可以根据需要添加更多国家
};

const instance = getCurrentInstance();
const $t = instance?.appContext.config.globalProperties.$t || ((key) => key);

const team = inject('team');
const {
	availableCredits,
	upcomingInvoice,
	currentBillingAmount,
	unpaidInvoices,
} = inject('billing');

const showBillingDetailsDialog = ref(false);
const showAddPrepaidCreditsDialog = ref(false);
const windowWidth = ref(window.innerWidth);

const isMobile = computed(() => windowWidth.value <= 768);
const buttonSize = computed(() => (isMobile.value ? 'medium' : 'medium'));

const currency = computed(() => (team.pg.currency == 'CNY' ? '¥' : '$'));

const billingDetails = createResource({
	url: 'jcloud.api.account.get_billing_information',
	cache: 'billingDetails',
	auto: true,
});

const changePaymentMode = createResource({
	url: 'jcloud.api.billing.change_payment_mode',
	onSuccess: () => setTimeout(() => team.reload(), 1000),
});

const billingDetailsSummary = computed(() => {
	let _billingDetails = billingDetails.data;
	if (!_billingDetails) return '';

	const { address_line1, city, state, country, pincode } =
		_billingDetails || {};
		
	// 转换国家名称为中文
	const displayCountry = countryToZh[country] || country;
	
	// 调整为中国用户习惯的地址格式
	// 中国地址格式：[国家] [省/自治区/直辖市] [市] [区/详细地址] [邮编]
	if (country === 'China') {
		// 中国地址使用中文格式
		return [
			displayCountry,
			state, // 省/自治区/直辖市
			city, // 市
			address_line1, // 详细地址
			pincode ? `邮编: ${pincode}` : '' // 邮编
		]
			.filter(Boolean)
			.join(' ');
	} else {
		// 国外地址保持原来的格式
		return [
			address_line1,
			city,
			state,
			displayCountry,
			pincode
		]
			.filter(Boolean)
			.join(', ');
	}
});

const paymentModeOptions = [
	{
		label: $t('Prepaid Credits'),
		value: 'Prepaid Credits',
		description: $t('Your monthly billing charges will be deducted from your account balance'),
		component: () =>
			h(DropdownItem, {
				label: $t('Prepaid Credits'),
				active: team.pg.payment_mode === 'Prepaid Credits',
				onClick: () => updatePaymentMode('Prepaid Credits'),
			}),
	},
	{
		label: $t('Paid By Partner'),
		value: 'Paid By Partner',
		condition: () => team.pg.partner_email,
		description: $t('Your partner will pay your monthly subscription fees'),
		component: () =>
			h(DropdownItem, {
				label: $t('Paid By Partner'),
				active: team.pg.payment_mode === 'Paid by Partner',
				onClick: () =>
					confirmDialog({
						title: $t('Confirm Payment Method'),
						message: $t('By changing the payment method to <strong>Paid By Partner</strong>, the following details will be shared with your partner:<br><br><li>Site/Server Name</li> <li>Plan Name</li><li>Site/Server Active Days</li><br>Are you sure you want to continue?'),
						primaryAction: {
							label: $t('Change Payment Method'),
							variant: 'solid',
							onClick: ({ hide }) => {
								updatePaymentMode('Paid By Partner');
								hide();
							},
						},
					}),
			}),
	},
];

const paymentMode = computed(() => {
	return paymentModeOptions.find((o) => o.value === team.pg.payment_mode);
});

const billingAddressButtonLabel = computed(() => {
	return billingDetailsSummary.value ? $t('Edit') : $t('Add Billing Address');
});

function handleResize() {
	windowWidth.value = window.innerWidth;
}

// 修改onMounted钩子，添加自动设置支付方式为余额支付的逻辑
onMounted(() => {
	handleResize();
	window.addEventListener('resize', handleResize);
	// 如果当前没有设置支付方式，自动设置为余额支付
	nextTick(() => {
		if (!team.pg.payment_mode) {
			updatePaymentMode('Prepaid Credits');
		}
	});
});

onUnmounted(() => {
	window.removeEventListener('resize', handleResize);
});

function payUnpaidInvoices() {
	let _unpaidInvoices = unpaidInvoices.data;
	if (_unpaidInvoices.length > 1) {
		showAddPrepaidCreditsDialog.value = true;
	} else {
		let invoice = _unpaidInvoices[0];
		showAddPrepaidCreditsDialog.value = true;
	}
}

const showMessage = ref(false);
function updatePaymentMode(mode) {
	showMessage.value = false;
	if (mode === 'Paid By Partner' && Boolean(unpaidInvoices.data.length > 0)) {
		if (unpaidInvoices.data) {
			payUnpaidInvoices();
			return;
		}
		if (currentBillingAmount.value) {
			const finalizeInvoicesDialog = defineAsyncComponent(
				() => import('./FinalizeInvoicesDialog.vue'),
			);
			renderDialog(h(finalizeInvoicesDialog));
			return;
		}
	}
	if (!changePaymentMode.loading) changePaymentMode.submit({ mode });
}
</script>

<style scoped>
.payment-details-card {
	border-radius: 12px;
	box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
	transition: box-shadow 0.2s ease;
}

.payment-details-card:hover {
	box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.balance-section,
.address-section {
	display: flex;
	flex-direction: column;
	gap: 16px;
}

.balance-info,
.address-info {
	flex: 1;
}

.balance-amount {
	font-size: 32px;
	font-weight: 700;
	color: var(--n-color-primary);
	line-height: 1.2;
}

.address-text {
	font-size: 14px;
	color: var(--n-text-color);
	line-height: 1.6;
	word-break: break-word;
}

.address-empty {
	font-size: 14px;
	color: var(--n-text-color-3);
	font-style: italic;
}

@media (min-width: 769px) {
	.balance-section,
	.address-section {
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
	}
}

@media (max-width: 768px) {
	.balance-amount {
		font-size: 24px;
	}
}
</style>