<template>
	<n-card v-if="!$team.pg?.jerp_partner" class="partner-card">
		<template #header>
			<div class="flex items-center justify-between">
				<div>
					<h3 class="text-lg font-semibold">{{ $t('Jingrow Partner') }}</h3>
					<p class="text-sm text-gray-600 mt-1">{{ $t('Jingrow partner associated with your account') }}</p>
				</div>
				<n-button
					v-if="!$team.pg?.partner_email"
					@click="showAddPartnerCodeDialog = true"
				>
					<template #icon>
						<n-icon><EditIcon /></n-icon>
					</template>
					{{ $t('Add Partner Code') }}
				</n-button>
				<n-button
					v-else
					type="error"
					@click="showRemovePartnerDialog = true"
				>
					<template #icon>
						<n-icon><TrashIcon /></n-icon>
					</template>
					{{ $t('Unlink Partner') }}
				</n-button>
			</div>
		</template>
		<div class="py-2">
			<p
				v-if="!$team.pg?.partner_email"
				class="text-sm text-gray-700"
			>
				{{ $t('Have a Jingrow partner referral code? Click') }}
				<strong>{{ $t('Add Partner Code') }}</strong>
				{{ $t('to associate with your partner team.') }}
			</p>
			<div v-else class="flex items-center gap-3">
				<div class="flex-1">
					<p class="text-sm font-medium text-gray-900">{{ partner_billing_name }}</p>
					<p class="text-sm text-gray-600">{{ $team.pg?.partner_email }}</p>
				</div>
			</div>
		</div>

		<!-- 添加合作伙伴代码对话框 -->
		<n-modal
			v-model:show="showAddPartnerCodeDialog"
			preset="card"
			:title="$t('Link Partner Account')"
			:style="modalStyle"
			:mask-closable="true"
			:close-on-esc="true"
		>
			<template #header>
				<span class="text-lg font-semibold">{{ $t('Link Partner Account') }}</span>
			</template>
			<n-space vertical :size="16">
				<p class="text-sm text-gray-700">
					{{ $t('Enter the partner code provided by your partner') }}
				</p>
				<n-alert type="info" :title="$t('Note')">
					{{ $t('After linking with a partner, the following information will be shared with your partner team:') }}
					<ul class="mt-2 ml-4 list-disc">
						<li>{{ $t('Billing Name') }}</li>
						<li>{{ $t('Monthly Billing Amount') }}</li>
					</ul>
				</n-alert>
				<n-form-item :label="$t('Partner Code')">
					<n-input
						v-model:value="code"
						:placeholder="$t('For example: rGjw3hJ81b')"
						:size="inputSize"
						@input="referralCodeChange"
					/>
				</n-form-item>
				<n-alert
					v-if="partnerExists"
					type="success"
					:title="$t('Referral code {code} belongs to {partner}', { code, partner })"
				/>
				<n-alert
					v-if="errorMessage"
					type="error"
					:title="errorMessage"
				/>
			</n-space>
			<template #action>
				<n-space :vertical="isMobile" :size="isMobile ? 12 : 16" class="w-full">
					<n-button @click="showAddPartnerCodeDialog = false" :block="isMobile" :size="buttonSize">
						{{ $t('Cancel') }}
					</n-button>
					<n-button
						type="primary"
						@click="handleAddPartnerCode"
						:loading="$resources.addPartnerCode.loading"
						:disabled="!partnerExists"
						:block="isMobile"
						:size="buttonSize"
					>
						{{ $t('Submit') }}
					</n-button>
				</n-space>
			</template>
		</n-modal>

		<!-- 移除合作伙伴对话框 -->
		<n-modal
			v-model:show="showRemovePartnerDialog"
			preset="dialog"
			:title="$t('Remove Partner')"
			:positive-text="$t('Remove')"
			:positive-button-props="{ type: 'error' }"
			:loading="$resources.removePartner.loading"
			:mask-closable="true"
			:close-on-esc="true"
			@positive-click="() => $resources.removePartner.submit()"
		>
			<p class="text-base">
				{{ $t('This will remove the partner associated with your account. Are you sure you want to remove this partner?') }}
			</p>
		</n-modal>
	</n-card>
</template>
<script>
import {
	NCard,
	NButton,
	NIcon,
	NModal,
	NSpace,
	NFormItem,
	NInput,
	NAlert,
} from 'naive-ui';
import { jingrowRequest, debounce } from 'jingrow-ui';
import { DashboardError } from '../../../utils/error';
import { toast } from 'vue-sonner';
import EditIcon from '~icons/lucide/edit';
import TrashIcon from '~icons/lucide/trash-2';

export default {
	name: 'AccountPartner',
	components: {
		NCard,
		NButton,
		NIcon,
		NModal,
		NSpace,
		NFormItem,
		NInput,
		NAlert,
		EditIcon,
		TrashIcon,
	},
	data() {
		return {
			showAddPartnerCodeDialog: false,
			showRemovePartnerDialog: false,
			code: '',
			partnerExists: false,
			partner: '',
			errorMessage: '',
		};
	},
	resources: {
		addPartnerCode() {
			return {
				url: 'jcloud.api.partner.add_partner',
				params: {
					referral_code: this.code,
				},
				onSuccess(data) {
					this.showAddPartnerCodeDialog = false;
					if (data === 'Request already sent') {
						toast.error(this.$t('Approval Request has already been sent to Partner'));
					} else {
						toast.success(this.$t('Approval Request has been sent to Partner'));
					}
				},
				onError() {
					throw new DashboardError(this.$t('Failed to add Partner Code'));
				},
			};
		},
		partnerName() {
			return {
				url: 'jcloud.api.partner.get_partner_name',
				auto: true,
				params: {
					partner_email: this.$team.pg?.partner_email,
				},
			};
		},
		removePartner() {
			return {
				url: 'jcloud.api.partner.remove_partner',
				onSuccess() {
					this.showRemovePartnerDialog = false;
					toast.success(this.$t('Partner removed successfully'));
				},
				onError() {
					throw new DashboardError(this.$t('Failed to remove partner'));
				},
			};
		},
	},
	computed: {
		isMobile() {
			return window.innerWidth <= 768;
		},
		modalStyle() {
			return {
				width: this.isMobile ? '95vw' : '800px',
				maxWidth: this.isMobile ? '95vw' : '90vw',
			};
		},
		inputSize() {
			return this.isMobile ? 'medium' : 'large';
		},
		buttonSize() {
			return this.isMobile ? 'medium' : 'medium';
		},
		partner_billing_name() {
			return this.$resources.partnerName?.data || '';
		},
	},
	methods: {
		referralCodeChange: debounce(async function (e) {
			let code = e.target.value;
			this.partnerExists = false;
			this.errorMessage = '';

			if (!code) {
				return;
			}

			try {
				let result = await jingrowRequest({
					url: 'jcloud.api.partner.validate_partner_code',
					params: { code: code },
				});

				let isValidCode = result[0];
				let partnerName = result[1];

				if (isValidCode) {
					this.partnerExists = true;
					this.partner = partnerName;
				} else {
					this.errorMessage = this.$t('{code} is an invalid referral code', { code });
				}
			} catch (error) {
				this.errorMessage = this.$t('Failed to validate partner code');
			}
		}, 500),
		handleAddPartnerCode() {
			if (this.partnerExists) {
				this.$resources.addPartnerCode.submit();
			}
		},
	},
};
</script>

<style scoped>
.partner-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;
}

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

@media (max-width: 768px) {
	.partner-card {
		border-radius: 8px;
	}

	:deep(.partner-card .n-card-header) {
		flex-direction: column;
		align-items: flex-start;
		gap: 12px;
	}

	:deep(.partner-card .n-card-header .n-button) {
		width: 100%;
		margin-top: 8px;
	}
}
</style>