<template>
	<n-modal
		v-model:show="showDialog"
		preset="card"
		:title="$t('Reset Password')"
		:style="modalStyle"
		:mask-closable="true"
		:close-on-esc="true"
		class="reset-password-dialog"
	>
		<template #header>
			<span class="text-lg font-semibold">{{ $t('Reset Password') }}</span>
		</template>
		<n-space vertical :size="20">
		<n-form-item v-if="!isResetMode" :label="$t('Current Password')">
			<n-input
				v-model:value="oldPassword"
				type="password"
				:placeholder="$t('Please enter current password')"
				:size="inputSize"
				show-password-on="click"
				class="w-full"
			/>
		</n-form-item>
		<n-form-item :label="$t('New Password')">
			<n-input
				v-model:value="newPassword"
				type="password"
				:placeholder="$t('Please enter new password')"
				:size="inputSize"
				show-password-on="click"
				class="w-full"
			/>
			<n-alert
				v-if="passwordStrengthMessage"
				:type="passwordStrengthClass === 'text-green-600' ? 'success' : 'error'"
				class="mt-2"
				:title="passwordStrengthMessage"
			/>
		</n-form-item>
		<n-form-item :label="$t('Confirm Password')">
			<n-input
				v-model:value="confirmPassword"
				type="password"
				:placeholder="$t('Please re-enter new password')"
				:size="inputSize"
				show-password-on="click"
				class="w-full"
			/>
			<n-alert
				v-if="passwordMismatchMessage"
				type="error"
				class="mt-2"
				:title="passwordMismatchMessage"
			/>
		</n-form-item>
			<n-alert
				v-if="error"
				type="error"
				:title="error"
			/>
		</n-space>
		<template #action>
			<n-space :vertical="isMobile" :size="isMobile ? 12 : 16" class="w-full">
				<n-button @click="hide" :block="isMobile" :size="buttonSize">
					{{ $t('Cancel') }}
				</n-button>
				<n-button
					type="primary"
					:loading="isLoading"
					:disabled="!isFormValid"
					@click="onConfirm"
					:block="isMobile"
					:size="buttonSize"
				>
					{{ $t('Confirm') }}
				</n-button>
			</n-space>
		</template>
	</n-modal>
</template>

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

export default {
	name: 'ResetPasswordDialog',
	components: {
		NModal,
		NFormItem,
		NInput,
		NSpace,
		NAlert,
		NButton,
	},
	props: {
		isResetMode: {
			type: Boolean,
			default: false
		},
		modelValue: {
			type: Boolean,
			default: false
		}
	},
	emits: ['update:modelValue'],
	expose: ['show', 'hide'],
	data() {
		return {
			error: null,
			isLoading: false,
			oldPassword: '',
			newPassword: '',
			confirmPassword: '',
			passwordStrengthMessage: '',
			passwordStrengthClass: '',
			passwordMismatchMessage: '',
			passwordStrengthTimeout: null
		};
	},
	computed: {
		showDialog: {
			get() {
				return this.modelValue;
			},
			set(value) {
				this.$emit('update:modelValue', value);
			}
		},
		isFormValid() {
			const hasNewPassword = this.newPassword && this.newPassword.length > 0;
			const hasConfirmPassword = this.confirmPassword && this.confirmPassword.length > 0;
			const passwordsMatch = this.newPassword === this.confirmPassword;
			const passwordsDifferent = this.oldPassword !== this.newPassword;
			
			if (this.isResetMode) {
				return hasNewPassword && hasConfirmPassword && passwordsMatch;
			} else {
				return this.oldPassword && hasNewPassword && hasConfirmPassword && passwordsMatch && passwordsDifferent;
			}
		},
		isMobile() {
			return window.innerWidth <= 768;
		},
		modalStyle() {
			return {
				width: this.isMobile ? '95vw' : '700px',
				maxWidth: this.isMobile ? '95vw' : '90vw',
			};
		},
		inputSize() {
			return this.isMobile ? 'medium' : 'large';
		},
		buttonSize() {
			return this.isMobile ? 'medium' : 'medium';
		},
	},
	watch: {
		newPassword() {
			this.checkPasswordStrength();
		},
		confirmPassword() {
			this.checkPasswordMismatch();
		},
		oldPassword() {
			this.checkPasswordMismatch();
		}
	},
	methods: {
		checkPasswordStrength() {
			if (this.passwordStrengthTimeout) {
				clearTimeout(this.passwordStrengthTimeout);
			}
			
			this.passwordStrengthTimeout = setTimeout(() => {
				if (!this.newPassword) {
					this.passwordStrengthMessage = '';
					return;
				}
				
				// 调用密码强度检查API
				this.$resources.checkPasswordStrength.submit({
					new_password: this.newPassword,
					old_password: this.oldPassword
				});
			}, 200);
		},
		
		checkPasswordMismatch() {
			if (this.oldPassword && this.newPassword && this.oldPassword === this.newPassword) {
				this.passwordMismatchMessage = this.$t('New password cannot be the same as current password');
				this.passwordStrengthMessage = '';
			} else if (this.confirmPassword && this.newPassword !== this.confirmPassword) {
				this.passwordMismatchMessage = this.$t('Passwords do not match');
				this.passwordStrengthMessage = '';
			} else {
				this.passwordMismatchMessage = '';
			}
		},
		
		async onConfirm() {
			this.error = null;
			
			if (!this.validateForm()) {
				return;
			}
			
			this.isLoading = true;
			try {
				await this.$resources.updatePassword.submit({
					old_password: this.oldPassword,
					new_password: this.newPassword,
					confirm_password: this.confirmPassword,
					logout_all_sessions: 1
				});
			} catch (error) {
				this.error = error.message || this.$t('Failed to update password');
			} finally {
				this.isLoading = false;
			}
		},
		
		validateForm() {
			if (!this.isResetMode && !this.oldPassword) {
				this.error = this.$t('Please enter current password');
				return false;
			}
			
			if (!this.newPassword) {
				this.error = this.$t('Please enter new password');
				return false;
			}
			
			if (this.newPassword !== this.confirmPassword) {
				this.error = this.$t('Passwords do not match');
				return false;
			}
			
			if (!this.isResetMode && this.oldPassword === this.newPassword) {
				this.error = this.$t('New password cannot be the same as current password');
				return false;
			}
			
			return true;
		},
		
		show() {
			this.showDialog = true;
			this.resetForm();
		},
		
		hide() {
			this.showDialog = false;
			this.resetForm();
		},
		
		resetForm() {
			this.oldPassword = '';
			this.newPassword = '';
			this.confirmPassword = '';
			this.error = null;
			this.passwordStrengthMessage = '';
			this.passwordStrengthClass = '';
			this.passwordMismatchMessage = '';
			
			if (this.passwordStrengthTimeout) {
				clearTimeout(this.passwordStrengthTimeout);
				this.passwordStrengthTimeout = null;
			}
		}
	},
	resources: {
		checkPasswordStrength() {
			return {
				url: 'jingrow.core.pagetype.user.user.test_password_strength',
				params: {
					old_password: this.oldPassword,
					new_password: this.newPassword
				},
				onSuccess(data) {
					if (data.message) {
						const score = data.message.score;
						const feedback = data.message.feedback;
						
						if (feedback.password_policy_validation_passed) {
							this.passwordStrengthMessage = this.$t('Password strength is good 👍');
							this.passwordStrengthClass = 'text-green-600';
						} else {
							let message = [];
							if (feedback.suggestions && feedback.suggestions.length) {
								message = message.concat(feedback.suggestions);
							} else if (feedback.warning) {
								message.push(feedback.warning);
							}
							message.push(this.$t('Tip: Password should contain symbols, numbers and uppercase letters'));
							this.passwordStrengthMessage = message.join(' ');
							this.passwordStrengthClass = 'text-red-600';
						}
					}
				},
				onError() {
					this.passwordStrengthMessage = '';
				}
			};
		},
		
		updatePassword() {
			return {
				url: 'jingrow.core.pagetype.user.user.update_password',
				onSuccess(data) {
					// 显示成功提示，5秒后自动消失
					toast.success(this.$t('Password updated successfully'), {
						duration: 3000,
						description: this.$t('Your password has been updated')
					});
					
					// 立即关闭对话框
					this.hide();
					
					// 如果有重定向消息，在关闭对话框后重定向
					if (data.message) {
						setTimeout(() => {
							window.location.href = data.message;
						}, 1000);
					}
				},
				onError(error) {
					if (error.status === 401) {
						this.error = this.$t('Current password is incorrect');
					} else {
						this.error = error.message || this.$t('Failed to update password');
					}
				}
			};
		}
	}
};
</script>

<style scoped>
:deep(.reset-password-dialog .n-card) {
	width: 700px;
	max-width: 90vw;
}

:deep(.reset-password-dialog .n-card-body) {
	padding: 24px;
}

:deep(.reset-password-dialog .n-form-item) {
	margin-bottom: 0;
}

:deep(.reset-password-dialog .n-input) {
	width: 100%;
}

:deep(.reset-password-dialog .n-form-item-label) {
	font-weight: 500;
	margin-bottom: 8px;
}

:deep(.reset-password-dialog .n-card__action) {
	padding: 16px 24px;
}

@media (max-width: 768px) {
	:deep(.reset-password-dialog .n-card) {
		width: 95vw !important;
		max-width: 95vw !important;
		margin: 20px auto;
		border-radius: 12px;
	}

	:deep(.reset-password-dialog .n-card-body) {
		padding: 20px 16px;
	}

	:deep(.reset-password-dialog .n-card__header) {
		padding: 16px;
		font-size: 18px;
	}

	:deep(.reset-password-dialog .n-card__action) {
		padding: 12px 16px;
	}

	:deep(.reset-password-dialog .n-space) {
		width: 100%;
	}

	:deep(.reset-password-dialog .n-button) {
		width: 100%;
		font-size: 16px;
		height: 44px;
	}

	:deep(.reset-password-dialog .n-form-item-label) {
		font-size: 14px;
		margin-bottom: 6px;
	}

	:deep(.reset-password-dialog .n-input) {
		font-size: 16px;
		height: 44px;
	}
}

/* 超小屏幕优化 */
@media (max-width: 480px) {
	:deep(.reset-password-dialog .n-card) {
		width: 100vw !important;
		max-width: 100vw !important;
		margin: 0;
		border-radius: 0;
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	:deep(.reset-password-dialog .n-card-body) {
		flex: 1;
		overflow-y: auto;
		padding: 16px;
	}

	:deep(.reset-password-dialog .n-card__action) {
		padding: 12px 16px;
		border-top: 1px solid var(--n-border-color);
	}
}
</style>
