<template>
    <div class="change-phone-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--readonly">
                        <input v-model="originalPhoneNumber" class="field-input" type="text" readonly />
                    </div>
                </div>

                <div class="form-field">
                    <div class="field-title">{{ t('手机号') }}</div>
                    <div class="field-input-wrapper">
                        <input v-model="phoneForm.phoneNumber" class="field-input" type="tel"
                            :placeholder="t('请输入手机号码')" />
                    </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="phoneForm.verifyCode" class="field-input" type="text"
                            :placeholder="t('请输入验证码')" />
                        <div class="verify-code-suffix">
                            <div class="verify-code-suffix__line"></div>
                            <button type="button" class="verify-code-button" :disabled="getCodeDisabled"
                                @click="handleGetVerifyCode">
                                {{ verifyCodeButtonText }}
                            </button>
                        </div>
                    </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 { computed, onUnmounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import AIDeskCoreInstance from '@tencentcloud/ai-desk-core';
import toast from '../../../../utils/toast';
import { parseUnknownError } from '../../../../utils/parseUnknownError';

const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const COUNTDOWN_SECONDS = 60;

const originalPhoneNumber = ref(
    typeof route.query.originalPhoneNumber === 'string' ? route.query.originalPhoneNumber : '',
);

const phoneForm = reactive({
    phoneNumber: '',
    verifyCode: '',
});

const countdown = ref(0);
const hasSentVerifyCode = ref(false);
let countdownTimer: ReturnType<typeof setInterval> | null = null;

const canSubmit = computed(() => {
    return phoneForm.phoneNumber.trim() !== '' && phoneForm.verifyCode.trim() !== '';
});

const getCodeDisabled = computed(() => {
    return phoneForm.phoneNumber.trim() === '' || countdown.value > 0;
});

const verifyCodeButtonText = computed(() => {
    if (countdown.value > 0) {
        return t('重新获取 {seconds}s', { seconds: countdown.value });
    }

    return hasSentVerifyCode.value ? t('重新获取') : t('发送验证码');
});

const clearCountdownTimer = () => {
    if (!countdownTimer) {
        return;
    }

    clearInterval(countdownTimer);
    countdownTimer = null;
};

const startCountdown = () => {
    clearCountdownTimer();
    hasSentVerifyCode.value = true;
    countdown.value = COUNTDOWN_SECONDS;

    countdownTimer = setInterval(() => {
        if (countdown.value <= 1) {
            countdown.value = 0;
            clearCountdownTimer();
            return;
        }

        countdown.value -= 1;
    }, 1000);
};

const handleGetVerifyCode = async () => {
    if (getCodeDisabled.value) {
        return;
    }

    const mobile = phoneForm.phoneNumber.trim();
    await AIDeskCoreInstance.userInfoService.getChangeMobileVerifyCode(mobile);
    startCountdown();
};

const handleConfirm = async () => {
    if (!canSubmit.value) {
        return;
    }

    try {
        await AIDeskCoreInstance.userInfoService.updateMobile(originalPhoneNumber.value, phoneForm.phoneNumber, phoneForm.verifyCode);
        router.back();
    } catch (error) {
        console.error(error);
        toast.error(parseUnknownError(error));
    }
};

onUnmounted(() => {
    clearCountdownTimer();
});
</script>

<style scoped>
.change-phone-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--readonly {
    background: #fff;
}

.field-input-wrapper--with-action {
    justify-content: space-between;
    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;
}

.verify-code-suffix {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    flex-shrink: 0;
}

.verify-code-suffix__line {
    width: 1px;
    height: 16px;
    background: #e6e9f0;
    flex-shrink: 0;
}

.verify-code-button {
    padding: 0;
    border: none;
    background: transparent;
    color: #0052d9;
    font-size: 14px;
    line-height: 22px;
    white-space: nowrap;
}

.verify-code-button:disabled {
    color: #b5b8be;
}

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