<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
import { REG_PWD } from '@/constants/reg';
import { fetchUpdateUserPassword } from '@/service/api';
import { useForm, useFormRules } from '@/hooks/common/form';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';
import { $t } from '@/locales';

defineOptions({ name: 'UserResetPasswordDialog' });

interface Props {
  userId?: number | null;
  username?: string | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate } = useForm();
const { createRequiredRule, createConfirmPwdRule } = useFormRules();

const submitting = ref(false);

const title = computed(() => $t('page.system.user.resetPassword'));
const displayUsername = computed(() => props.username?.trim() || $t('common.noData'));

const model = ref({
  password: '',
  confirmPassword: ''
});

const rules = computed<Record<'password' | 'confirmPassword', App.Global.FormRule[]>>(() => ({
  password: [
    createRequiredRule($t('page.system.user.form.newPassword')),
    { pattern: REG_PWD, message: $t('form.pwd.invalid') }
  ],
  confirmPassword: createConfirmPwdRule(model.value.password)
}));

function initModel() {
  model.value.password = '';
  model.value.confirmPassword = '';
}

function closeDialog() {
  visible.value = false;
}

async function handleSubmit() {
  if (!props.userId) {
    return;
  }

  await validate();

  submitting.value = true;

  const { error } = await fetchUpdateUserPassword({
    id: props.userId,
    password: model.value.password.trim()
  });

  submitting.value = false;

  if (error) {
    return;
  }

  window.$message?.success($t('common.updateSuccess'));
  closeDialog();
  emit('submitted');
}

watch(visible, async value => {
  if (!value) {
    return;
  }

  initModel();
  await nextTick();
  formRef.value?.clearValidate();
});
</script>

<template>
  <BusinessFormDialog
    v-model="visible"
    :title="title"
    preset="sm"
    :confirm-loading="submitting"
    :scrollbar="false"
    @confirm="handleSubmit"
  >
    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top" autocomplete="off">
      <input class="business-form-autofill-guard" type="text" name="fake-username" autocomplete="username" />
      <input class="business-form-autofill-guard" type="password" name="fake-password" autocomplete="new-password" />

      <ElRow :gutter="16">
        <ElCol :span="24">
          <ElFormItem :label="$t('page.system.user.userName')">
            <ElInput :model-value="displayUsername" disabled />
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem :label="$t('page.system.user.newPassword')" prop="password">
            <ElInput
              v-model="model.password"
              name="system-user-reset-password"
              show-password
              autocomplete="new-password"
              :placeholder="$t('page.system.user.form.newPassword')"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem :label="$t('page.system.user.confirmPassword')" prop="confirmPassword">
            <ElInput
              v-model="model.confirmPassword"
              name="system-user-reset-confirm-password"
              show-password
              autocomplete="new-password"
              :placeholder="$t('page.system.user.form.confirmPassword')"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>
  </BusinessFormDialog>
</template>

<style scoped>
.business-form-autofill-guard {
  position: absolute;
  width: 1px;
  height: 1px;
  padding: 0;
  margin: -1px;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  border: 0;
  opacity: 0;
  pointer-events: none;
}
</style>
