<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useFundPasswordStore } from '@/stores/fundPassword'
import { useSecurityStore } from '@/stores/security'
import { useToast } from '@/composables/useToast'
import { useI18n } from 'vue-i18n'
import { validateFundPasswordRule } from '@/utils/passwordRules'

const { t } = useI18n()
const router = useRouter()
const fundStore = useFundPasswordStore()
const securityStore = useSecurityStore()
const { loading, sendingCode, codeCountdown } = storeToRefs(fundStore)
const toast = useToast()

const password = ref('')
const confirm = ref('')
const emailCode = ref('')
const localError = ref('')

const isResetMode = computed(() => securityStore.auth?.fundsVerified === '1')

onMounted(async () => {
  try {
    await securityStore.fetchSecuritySetting()
  } catch {
    // 仍允许用户尝试提交
  }
})

onUnmounted(() => {
  fundStore.stopCountdown()
})

async function onSendCode() {
  if (!isResetMode.value) return
  localError.value = ''
  try {
    await fundStore.sendResetEmailCode()
    toast.success(t('security.codeSent'))
  } catch {
    localError.value = fundStore.error ?? t('error.sendFailed')
  }
}

async function onSubmit() {
  localError.value = ''
  const errPwd = validateFundPasswordRule(password.value)
  if (errPwd) {
    localError.value = errPwd
    return
  }
  if (password.value !== confirm.value) {
    localError.value = t('error.passwordMismatch')
    return
  }
  if (isResetMode.value) {
    if (!/^\d{6}$/.test(emailCode.value)) {
      localError.value = t('error.sixDigitCode')
      return
    }
    try {
      await fundStore.resetFundPassword(password.value, emailCode.value)
      toast.success(t('security.fundPasswordUpdated'))
      router.replace('/account/security')
    } catch {
      localError.value = fundStore.error ?? t('error.operationFailed')
    }
  } else {
    try {
      await fundStore.setInitialFundPassword(password.value)
      toast.success(t('security.fundPasswordSet'))
      router.replace('/account/security')
    } catch {
      localError.value = fundStore.error ?? t('error.operationFailed')
    }
  }
}
</script>

<template>
  <main class="page-main">
    <div class="page-container sub-wrap">
      <div class="page-header">
        <RouterLink to="/account/security" class="back-link">{{ t('security.back') }}</RouterLink>
        <h1 class="page-title">{{ isResetMode ? t('security.resetFundPassword') : t('security.setFundPassword') }}</h1>
      </div>

      <div class="form-card dark-card">
        <p v-if="!isResetMode" class="hint">{{ t('security.fundPasswordHint') }}</p>
        <p v-else class="hint">{{ t('security.fundPasswordResetHint') }}</p>

        <div class="form-group">
          <label class="form-label">{{ isResetMode ? t('security.newFundPassword') : t('security.fundPassword') }}</label>
          <input v-model="password" type="password" class="form-input" autocomplete="new-password" />
        </div>
        <div class="form-group">
          <label class="form-label">{{ t('security.confirmFundPassword') }}</label>
          <input v-model="confirm" type="password" class="form-input" autocomplete="new-password" />
        </div>

        <template v-if="isResetMode">
          <div class="form-group">
            <label class="form-label">{{ t('security.emailCode') }}</label>
            <div class="code-row">
              <input
                v-model="emailCode"
                type="text"
                maxlength="6"
                class="form-input"
                placeholder="6"
                @input="emailCode = emailCode.replace(/\D/g, '')"
              />
              <button
                type="button"
                class="send-code-btn"
                :disabled="sendingCode || codeCountdown > 0"
                @click="onSendCode"
              >
                {{ codeCountdown > 0 ? `${codeCountdown}s` : t('security.sendCode') }}
              </button>
            </div>
          </div>
        </template>

        <p v-if="localError" class="form-error">{{ localError }}</p>

        <div class="actions">
          <button type="button" class="btn-cancel" @click="router.back()">{{ t('common.cancel') }}</button>
          <button type="button" class="btn-confirm" :disabled="loading" @click="onSubmit">
            {{ loading ? t('security.submitting') : t('common.confirm') }}
          </button>
        </div>
      </div>
    </div>
  </main>
</template>

<style scoped>
.sub-wrap {
  padding-top: var(--space-8);
  padding-bottom: var(--space-16);
  max-width: 480px;
}
.page-header {
  margin-bottom: var(--space-8);
}
.back-link {
  font-size: var(--text-small);
  color: var(--color-text-secondary);
  display: inline-block;
  margin-bottom: var(--space-3);
}
.page-title {
  font-size: var(--text-h1);
  font-weight: var(--fw-bold);
  color: var(--color-text-primary);
}
.form-card {
  padding: var(--space-6);
}
.hint {
  font-size: var(--text-small);
  color: var(--color-text-secondary);
  margin-bottom: var(--space-6);
  line-height: 1.5;
}
.form-group {
  margin-bottom: var(--space-4);
}
.form-label {
  display: block;
  font-size: var(--text-small);
  color: var(--color-text-secondary);
  margin-bottom: var(--space-2);
}
.form-input {
  width: 100%;
  box-sizing: border-box;
  background: var(--color-bg-card);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  padding: var(--space-3) var(--space-4);
  color: var(--color-text-primary);
  outline: none;
}
.form-input:focus {
  border-color: var(--color-primary);
}
.form-error {
  font-size: var(--text-small);
  color: var(--color-down);
  margin-bottom: var(--space-4);
}
.code-row {
  display: flex;
  gap: var(--space-3);
}
.code-row .form-input {
  flex: 1;
}
.send-code-btn {
  white-space: nowrap;
  padding: 0 var(--space-4);
  background: transparent;
  border: 1px solid var(--color-primary);
  border-radius: var(--radius-md);
  color: var(--color-primary);
  font-size: var(--text-small);
  cursor: pointer;
  flex-shrink: 0;
}
.send-code-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
.actions {
  display: flex;
  gap: var(--space-3);
  margin-top: var(--space-6);
}
.btn-cancel {
  flex: 1;
  padding: var(--space-3);
  background: var(--color-bg-card);
  border: 1px solid var(--color-border);
  border-radius: var(--radius-md);
  color: var(--color-text-secondary);
  cursor: pointer;
}
.btn-confirm {
  flex: 2;
  padding: var(--space-3);
  background: var(--color-primary);
  border: none;
  border-radius: var(--radius-md);
  color: #000;
  font-weight: var(--fw-semibold);
  cursor: pointer;
}
.btn-confirm:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
