<template>
    <div class="change-password-page">
        <header class="page-header">
            <button class="back-button" type="button" :aria-label="t('返回')" @click="router.back()">
                &lt;
            </button>
            <div class="page-title">{{ t('修改密码') }}</div>
        </header>

        <div class="page-content">
            <div class="form-card">
                <div class="form-field">
                    <div class="field-title">{{ t('当前密码') }}</div>
                    <div class="field-input-wrapper field-input-wrapper--with-action">
                        <input v-model="passwordForm.oldPassword" class="field-input"
                            :type="passwordVisible.oldPassword ? 'text' : 'password'"
                            @blur="fieldTouched.oldPassword = true" />
                        <button type="button" class="password-visibility-button"
                            :aria-label="passwordVisible.oldPassword ? t('隐藏当前密码') : t('显示当前密码')"
                            @click="togglePasswordVisible('oldPassword')">
                            <img :src="passwordVisible.oldPassword ? showIcon : hideIcon"
                                class="password-visibility-icon" alt="" />
                        </button>
                    </div>
                    <div v-if="displayPasswordErrors.oldPassword" class="password-error">{{
                        displayPasswordErrors.oldPassword }}</div>
                </div>

                <div class="form-field">
                    <div class="field-title">{{ t('新密码') }}</div>
                    <div class="field-input-wrapper field-input-wrapper--with-action">
                        <input v-model="passwordForm.newPassword" class="field-input"
                            :type="passwordVisible.newPassword ? 'text' : 'password'"
                            @blur="fieldTouched.newPassword = true" />
                        <button type="button" class="password-visibility-button"
                            :aria-label="passwordVisible.newPassword ? t('隐藏新密码') : t('显示新密码')"
                            @click="togglePasswordVisible('newPassword')">
                            <img :src="passwordVisible.newPassword ? showIcon : hideIcon"
                                class="password-visibility-icon" alt="" />
                        </button>
                    </div>
                    <div v-if="displayPasswordErrors.newPassword" class="password-error">{{
                        displayPasswordErrors.newPassword }}</div>
                </div>

                <div class="form-field">
                    <div class="field-title">{{ t('重复密码') }}</div>
                    <div class="field-input-wrapper field-input-wrapper--with-action">
                        <input v-model="passwordForm.confirmPassword" class="field-input"
                            :type="passwordVisible.confirmPassword ? 'text' : 'password'"
                            @blur="fieldTouched.confirmPassword = true" />
                        <button type="button" class="password-visibility-button"
                            :aria-label="passwordVisible.confirmPassword ? t('隐藏重复密码') : t('显示重复密码')"
                            @click="togglePasswordVisible('confirmPassword')">
                            <img :src="passwordVisible.confirmPassword ? showIcon : hideIcon"
                                class="password-visibility-icon" alt="" />
                        </button>
                    </div>
                    <div v-if="displayPasswordErrors.confirmPassword" class="password-error">{{
                        displayPasswordErrors.confirmPassword }}</div>
                </div>
            </div>
        </div>

        <div class="page-footer">
            <button type="button" class="submit-button" :class="{ 'submit-button--disabled': !canSubmit }"
                :disabled="!canSubmit" @click="handleConfirm">
                {{ t('确定') }}
            </button>
        </div>
    </div>
</template>

<script setup lang="ts">
import AIDeskCoreInstance, { StoreName } from '@tencentcloud/ai-desk-core';
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import hideIcon from './hide.svg';
import showIcon from './show.svg';
import toast from '../../../../utils/toast';
import { parseUnknownError } from '../../../../utils/parseUnknownError';

const router = useRouter();
const { t } = useI18n();

const passwordForm = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
});
const fieldTouched = reactive({
    oldPassword: false,
    newPassword: false,
    confirmPassword: false,
});
const passwordVisible = reactive({
    oldPassword: false,
    newPassword: false,
    confirmPassword: false,
});
const currnetUserId = ref('');

onMounted(() => {
    AIDeskCoreInstance.coreStore.watch(StoreName.USERINFO, {
        userId: onCurrentUserIdUpdated,
    });
});

onUnmounted(() => {
    AIDeskCoreInstance.coreStore.unwatch(StoreName.USERINFO, {
        userId: onCurrentUserIdUpdated,
    });
});

const onCurrentUserIdUpdated = (userId: string) => {
    currnetUserId.value = userId;
};

const validatePassword = (password: string) => {
    const re = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&^()])[A-Za-z\d@$!%*#?&^()]{8,20}$/;
    return re.test(password);
};

const togglePasswordVisible = (field: keyof typeof passwordVisible) => {
    passwordVisible[field] = !passwordVisible[field];
};

const passwordErrors = computed(() => {
    const errors: {
        oldPassword?: string;
        newPassword?: string;
        confirmPassword?: string;
    } = {
        oldPassword: undefined,
        newPassword: undefined,
        confirmPassword: undefined,
    };

    if (!passwordForm.oldPassword) {
        errors.oldPassword = t('请输入当前密码');
    }

    if (!passwordForm.newPassword) {
        errors.newPassword = t('请输入密码');
    }

    if (!passwordForm.confirmPassword) {
        errors.confirmPassword = t('请输入重复密码');
    }

    if (passwordForm.newPassword) {
        if (passwordForm.newPassword === currnetUserId.value) {
            errors.newPassword = t('密码不能与您的邮箱地址相同');
        }

        if (!validatePassword(passwordForm.newPassword)) {
            errors.newPassword = t('密码需要同时包含数字、字母以及特殊符号');
        }

        if (passwordForm.newPassword.length < 8 || passwordForm.newPassword.length > 20) {
            errors.newPassword = t('密码长度必须在8-20位之间');
        }

        if (
            passwordForm.confirmPassword
            && passwordForm.newPassword !== passwordForm.confirmPassword
        ) {
            errors.confirmPassword = t('两次输入的密码不一致');
        }
    }

    return errors;
});

const displayPasswordErrors = computed(() => ({
    oldPassword: fieldTouched.oldPassword ? passwordErrors.value.oldPassword : undefined,
    newPassword: fieldTouched.newPassword ? passwordErrors.value.newPassword : undefined,
    confirmPassword: fieldTouched.confirmPassword ? passwordErrors.value.confirmPassword : undefined,
}));

const canSubmit = computed(() => {
    return passwordForm.oldPassword !== ''
        && passwordForm.newPassword !== ''
        && passwordForm.confirmPassword !== ''
        && !passwordErrors.value.oldPassword
        && !passwordErrors.value.newPassword
        && !passwordErrors.value.confirmPassword;
});

const handleConfirm = async () => {
    fieldTouched.oldPassword = true;
    fieldTouched.newPassword = true;
    fieldTouched.confirmPassword = true;

    if (!canSubmit.value) {
        return;
    }

    try {
        await AIDeskCoreInstance.userInfoService.changePassword(
            passwordForm.oldPassword,
            passwordForm.newPassword,
        );
        router.back();
    } catch (error) {
        console.error(error);
        toast.error(parseUnknownError(error));
    }
};
</script>

<style scoped>
.change-password-page {
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #fff;
}

.page-header {
    height: 56px;
    padding: 0 16px;
    display: flex;
    align-items: center;
    gap: 12px;
    background: #fff;
    border-bottom: 1px solid #f2f3f5;
    box-sizing: border-box;
    flex-shrink: 0;
}

.back-button {
    width: 32px;
    height: 32px;
    padding: 0;
    border: 1px solid #e7e8ea;
    border-radius: 999px;
    background: #fff;
    color: #1d2129;
    font-size: 18px;
    line-height: 1;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    flex-shrink: 0;
}

.page-title {
    color: #1d2129;
    font-size: 18px;
    font-weight: 600;
    line-height: 26px;
    text-align: left;
}

.page-content {
    flex: 1;
    padding: 16px;
    background: #fff;
    box-sizing: border-box;
}

.form-card {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.form-field {
    display: flex;
    flex-direction: column;
}

.field-title {
    font-size: 14px;
    line-height: 22px;
    color: #1d2129;
    margin-bottom: 12px;
}

.field-input-wrapper {
    width: 100%;
    border: 1px solid #E6E9F0;
    border-radius: 19px;
    background: #fff;
    padding: 8px 12px;
    display: flex;
    align-items: center;
    min-height: 38px;
    box-sizing: border-box;
}

.field-input-wrapper--with-action {
    gap: 8px;
}

.field-input {
    flex: 1;
    min-width: 0;
    height: 22px;
    padding: 0;
    border: none;
    outline: none;
    background: transparent;
    color: #1d2129;
    font-size: 14px;
    line-height: 22px;
}

.field-input::placeholder {
    color: #86909c;
}

.password-error {
    margin-top: 8px;
    color: #d54941;
    font-size: 12px;
    line-height: 20px;
}

.page-footer {
    padding: 12px 0 24px;
    display: flex;
    justify-content: center;
    background: #fff;
    flex-shrink: 0;
}

.submit-button {
    width: 80%;
    height: 44px;
    border: none;
    border-radius: 22px;
    background: #000;
    color: #fff;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
}

.submit-button--disabled {
    background: rgba(0, 0, 0, 0.05999999865889549);
    cursor: not-allowed;
}

.password-visibility-button {
    padding: 0;
    border: none;
    background: transparent;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    flex-shrink: 0;
}

.password-visibility-icon {
    width: 16px;
    height: 16px;
    display: block;
}
</style>