<template>
	<div>
		<n-spin :show="$resources.qrUrl.loading">
			<n-space vertical :size="24">
				<!-- 禁用 2FA 模式 -->
				<div v-if="is2FAEnabled && $route.name !== 'Enable2FA'">
					<n-alert
						type="error"
						:title="$t('If you disable two-factor authentication, your account will become insecure')"
						class="mb-4"
					/>

					<n-card class="mb-4">
						<h3 class="text-lg font-semibold mb-3">{{ $t('Steps to Disable Two-Factor Authentication') }}</h3>
						<ol class="ml-4 list-decimal space-y-2 text-sm text-gray-700">
							<li>{{ $t('Open the authenticator app') }}</li>
							<li>{{ $t('Enter the code from the app below') }}</li>
						</ol>
					</n-card>

				<n-form-item :label="$t('Verify the code in the app to disable two-factor authentication')" class="mt-6">
					<n-input
						v-model:value="totpCode"
						:placeholder="$t('Enter the code from the authenticator app')"
						size="large"
						class="w-full"
					/>
				</n-form-item>
				</div>

				<!-- 启用 2FA 模式 -->
				<div v-else>
					<!-- QR 码 -->
					<div class="flex justify-center">
						<VueQrcode
							v-if="qrUrl"
							class="mx-auto"
							:value="qrUrl"
							type="image/png"
							:color="{ dark: '#000000ff', light: '#ffffffff' }"
							:size="240"
						/>
					</div>

					<!-- 步骤说明 -->
					<n-card>
						<h3 class="text-lg font-semibold mb-3">{{ $t('Steps to Enable Two-Factor Authentication') }}</h3>
						<ol class="ml-4 list-decimal space-y-2 text-sm text-gray-700 mb-4">
							<li>{{ $t('Download an authenticator app on your phone, such as Alibaba Cloud APP, etc.') }}</li>
							<li>{{ $t('Scan the QR code') }}</li>
							<li>{{ $t('Enter the code from the authenticator app below') }}</li>
						</ol>
						<n-alert type="warning" class="mt-4">
							<template #header>
								<strong>{{ $t('Note') }}:</strong>
							</template>
							{{ $t('If you cannot access the authenticator app, your account will be locked. Please ensure you back up your vault/key.') }}
						</n-alert>
					</n-card>

					<!-- Setup Key -->
					<n-card v-if="showSetupKey">
						<h3 class="text-lg font-semibold mb-2">{{ $t('Setup Key') }}</h3>
						<p class="text-sm font-mono text-gray-700 break-all">
							{{ setupKey }}
						</p>
					</n-card>

				<!-- 验证码输入 -->
				<n-form-item :label="$t('Verify the code in the app to enable two-factor authentication')" class="mt-6">
					<n-input
						v-model:value="totpCode"
						:placeholder="$t('Enter the code from the authenticator app')"
						size="large"
						class="w-full"
					/>
				</n-form-item>
				</div>

				<!-- 操作按钮 -->
				<n-button
					v-if="!is2FAEnabled"
					type="primary"
					size="large"
					block
					:disabled="!totpCode"
					:loading="$resources.enable2FA.loading"
					@click="enable2FA"
				>
					{{ $t('Enable Two-Factor Authentication') }}
				</n-button>
				<n-button
					v-else
					type="error"
					size="large"
					block
					:disabled="!totpCode"
					:loading="$resources.disable2FA.loading"
					@click="disable2FA"
				>
					{{ $t('Disable Two-Factor Authentication') }}
				</n-button>
			</n-space>
		</n-spin>
	</div>
</template>

<script>
import {
	NSpace,
	NAlert,
	NCard,
	NFormItem,
	NInput,
	NButton,
	NSpin,
} from 'naive-ui';
import VueQrcode from 'vue-qrcode';
import { toast } from 'vue-sonner';

export default {
	emits: ['enabled', 'disabled'],
	data() {
		return {
			qrUrl: '', // not storing as computed property to avoid re-fetching on dialog close
			totpCode: '',
			showSetupKey: false
		};
	},
	components: {
		NSpace,
		NAlert,
		NCard,
		NFormItem,
		NInput,
		NButton,
		NSpin,
		VueQrcode
	},
	methods: {
		enable2FA() {
			toast.promise(
				this.$resources.enable2FA.submit({
					totp_code: this.totpCode
				}),
				{
					loading: this.$t('Enabling two-factor authentication...'),
					success: () => {
						this.totpCode = '';

						// avoid flickering of 2FA dialog
						setTimeout(() => {
							this.$team.reload();
						}, 500);
						this.$emit('enabled');

						return this.$t('Two-factor authentication enabled successfully');
					},
					error(err) {
						if (err.messages) {
							if (err.messages.includes('Invalid TOTP code')) {
								return this.$t('Invalid TOTP code, please try again');
							} else {
								return err.messages.join('.');
							}
						} else {
							return this.$t('Failed to enable two-factor authentication');
						}
					}
				}
			);
		},
		disable2FA() {
			toast.promise(
				this.$resources.disable2FA.submit({
					totp_code: this.totpCode
				}),
				{
					loading: this.$t('Disabling two-factor authentication...'),
					success: () => {
						this.totpCode = '';

						// avoid flickering of 2FA dialog
						setTimeout(() => {
							this.$team.reload();
						}, 500);

						this.$emit('disabled');

						return this.$t('Two-factor authentication disabled successfully');
					},
					error(err) {
						if (err.messages) {
							if (err.messages.includes('Invalid TOTP code')) {
								return this.$t('Invalid TOTP code, please try again');
							} else {
								return err.messages.join('.');
							}
						} else {
							return this.$t('Failed to disable two-factor authentication');
						}
					}
				}
			);
		}
	},
	resources: {
		qrUrl() {
			return {
				url: 'jcloud.api.account.get_2fa_qr_code_url',
				auto: true,
				onSuccess(qr_code_url) {
					this.qrUrl = qr_code_url;
				}
			};
		},
		enable2FA() {
			return {
				url: 'jcloud.api.account.enable_2fa'
			};
		},
		disable2FA() {
			return {
				url: 'jcloud.api.account.disable_2fa'
			};
		}
	},
	computed: {
		setupKey() {
			if (!this.qrUrl) return null;
			return this.qrUrl.match(/secret=(.*?)&issuer/)[1];
		},
		is2FAEnabled() {
			return this.$team.pg?.user_info?.is_2fa_enabled;
		}
	}
};
</script>