<script setup>
import { ref, onMounted, defineProps, inject } from "vue";
import * as yup from "yup";
import "yup-phone-lite";
import useFormErrorMessage from "@/hooks/useFormErrorMessage";
import { changePassword } from "@/apis/account";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { openToast } = inject("app_toast");

const props = defineProps({
  account: Object,
});

const formState = ref({
  Password: "",
});
const showPassword = ref(false);
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

let userSchema = yup.object({
  Password: yup.string().required(t("button.required")),
});

const { formErrorMsg, handleSubmit, handleErrorReset } =
  useFormErrorMessage(userSchema);

const onCancel = () => {
  handleErrorReset();
  account_user_password_modal.close();
};

const onOk = async () => {
  const value = await handleSubmit(userSchema, formState.value);
  const res = await changePassword({ ...value, Id: props.account.Id });
  if (res.isSuccess) {
    onCancel();
  } else {
    openToast("error", res.msg, "#account_user_password_modal");
  }
};
</script>

<template>
  <Modal
    id="account_user_password_modal"
    :title="t('accountManagement.change_password')"
    :onCancel="onCancel"
   :width="710"
  >
    <template #modalContent>
      <p class="mt-10 text-3xl">{{ account.Name }}</p>
      <form ref="form" class="mt-5 w-full flex flex-wrap justify-between">
        <Input
          :value="formState"
          class="relative my-2"
          name="Password"
          :type="showPassword ? 'text' : 'password'"
        >
          <template #topLeft>{{
            $t("accountManagement.change_password")
          }}</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ formErrorMsg.Password }}
            </span></template
          >
          <template #bottomRight>
            <FontAwesomeIcon
              :icon="['fas', showPassword ? 'eye-slash' : 'eye']"
              class="fa-2x absolute top-14 right-0 transform -translate-x-1/2 cursor-pointer"
              @click="togglePasswordVisibility"
            />
          </template>
        </Input>
      </form>
    </template>
    <template #modalAction>
      <button
        type="reset"
        class="btn btn-outline-success mr-2"
        @click.prevent="onCancel"
      >
        {{ $t("button.cancel") }}
      </button>
      <button
        type="submit"
        class="btn btn-outline-success"
        @click.stop.prevent="onOk"
      >
        {{ $t("button.submit") }}
      </button>
    </template>
  </Modal>
</template>

<style lang="scss" scoped></style>
