<script setup lang="ts">
import { computed, ref } from 'vue';
import { useRouterPush } from '@/hooks/common/router';
import { useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';

defineOptions({ name: 'ResetPwd' });

const { toggleLoginModule } = useRouterPush();
const { formRef, validate } = useForm();

interface FormModel {
  phone: string;
  code: string;
  password: string;
  confirmPassword: string;
}

const model = ref<FormModel>({
  phone: '',
  code: '',
  password: '',
  confirmPassword: ''
});

type RuleRecord = Partial<Record<keyof FormModel, App.Global.FormRule[]>>;

const rules = computed<RuleRecord>(() => {
  const { formRules, createConfirmPwdRule } = useFormRules();

  return {
    phone: formRules.phone,
    password: formRules.pwd,
    confirmPassword: createConfirmPwdRule(model.value.password)
  };
});

async function handleSubmit() {
  await validate();
  // request to reset password
  window.$message?.success($t('page.login.common.validateSuccess'));
}
</script>

<template>
  <ElForm ref="formRef" :model="model" :rules="rules" size="large" @keyup.enter="handleSubmit">
    <ElFormItem prop="phone">
      <ElInput v-model="model.phone" :placeholder="$t('page.login.common.phonePlaceholder')">
        <template #prefix>
          <SvgIcon icon="mdi:cellphone" />
        </template>
      </ElInput>
    </ElFormItem>
    <ElFormItem prop="code">
      <ElInput v-model="model.code" :placeholder="$t('page.login.common.codePlaceholder')">
        <template #prefix>
          <SvgIcon icon="mdi:shield-check-outline" />
        </template>
      </ElInput>
    </ElFormItem>
    <ElFormItem prop="password">
      <ElInput
        v-model="model.password"
        type="password"
        show-password
        :placeholder="$t('page.login.common.passwordPlaceholder')"
      >
        <template #prefix>
          <SvgIcon icon="mdi:lock-outline" />
        </template>
      </ElInput>
    </ElFormItem>
    <ElFormItem prop="confirmPassword">
      <ElInput
        v-model="model.confirmPassword"
        type="password"
        show-password
        :placeholder="$t('page.login.common.confirmPasswordPlaceholder')"
      >
        <template #prefix>
          <SvgIcon icon="mdi:lock-check-outline" />
        </template>
      </ElInput>
    </ElFormItem>
    <ElButton type="primary" size="large" class="login-submit-button" @click="handleSubmit">
      {{ $t('common.confirm') }}
    </ElButton>
    <ElButton size="large" class="login-back-button" @click="toggleLoginModule('pwd-login')">
      {{ $t('page.login.common.back') }}
    </ElButton>
  </ElForm>
</template>

<style scoped>
.login-back-button {
  width: 100%;
  height: 44px;
  margin-top: 14px;
  margin-left: 0;
  border-radius: 10px;
}
</style>
