<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useChangePasswordStore } from '@/stores/changePassword'
import { useToast } from '@/composables/useToast'
import { useI18n } from 'vue-i18n'
import { LOGIN_PASSWORD_FIELD_PLACEHOLDER, validateLoginPasswordRule } from '@/utils/passwordRules'

const { t } = useI18n()
const router = useRouter()
const store = useChangePasswordStore()
const { loading, sendingCode, codeCountdown } = storeToRefs(store)
const toast = useToast()

const oldPassword = ref('')
const newPassword = ref('')
const confirmPassword = ref('')
const vcode = ref('')
const localError = ref('')

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

async function onSendCode() {
  localError.value = ''
  try {
    await store.sendEmailCode()
    toast.success(t('security.codeSent'))
  } catch {
    localError.value = store.error ?? t('error.sendFailed')
  }
}

async function onSubmit() {
  localError.value = ''
  if (!oldPassword.value) {
    localError.value = t('error.currentPasswordRequired')
    return
  }
  const errNew = validateLoginPasswordRule(newPassword.value)
  if (errNew) {
    localError.value = errNew
    return
  }
  if (newPassword.value !== confirmPassword.value) {
    localError.value = t('error.passwordMismatch')
    return
  }
  if (!/^\d{6}$/.test(vcode.value)) {
    localError.value = t('error.sixDigitCode')
    return
  }
  try {
    await store.submitChangePassword(oldPassword.value, newPassword.value, vcode.value)
    toast.success(t('security.changeSuccess'))
    router.back()
  } catch {
    localError.value = store.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">{{ t('security.changeLoginPassword') }}</h1>
      </div>

      <div class="form-card dark-card">
        <p class="hint">{{ t('security.changePasswordHint') }}</p>

        <div class="form-group">
          <label class="form-label">{{ t('security.currentPassword') }}</label>
          <input v-model="oldPassword" type="password" class="form-input" autocomplete="current-password" />
        </div>
        <div class="form-group">
          <label class="form-label">{{ t('security.newPassword') }}</label>
          <input
            v-model="newPassword"
            type="password"
            class="form-input"
            :placeholder="LOGIN_PASSWORD_FIELD_PLACEHOLDER"
            autocomplete="new-password"
          />
        </div>
        <div class="form-group">
          <label class="form-label">{{ t('security.confirmNewPassword') }}</label>
          <input v-model="confirmPassword" type="password" class="form-input" autocomplete="new-password" />
        </div>
        <div class="form-group">
          <label class="form-label">{{ t('security.emailCode') }}</label>
          <div class="code-row">
            <input
              v-model="vcode"
              type="text"
              maxlength="6"
              class="form-input"
              placeholder="6"
              @input="vcode = vcode.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>

        <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('security.confirmChange') }}
          </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);
  font-size: var(--text-body);
  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>
