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

const props = defineProps({
  formState: Object,
  reset: Function,
  getData: Function,
});
const showPassword = ref(false);
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

let userSchema = ref(
  yup.object({
    Account: yup.string().required(t("button.required")),
    Name: yup.string().required(t("button.required")),
    Email: yup
      .string()
      .email(t("button.email_format"))
      .required(t("button.required")),
    Phone: yup
      .string()
      .phone("TW", t("button.phone_format"))
      .required(t("button.required")),
    RoleId: yup.string().required(t("button.required")),
    Password: yup
      .string()
      .required(t("button.required"))
      .matches(/^(?=.{8})(?=.*[A-Za-z])(?=.*\d)/g, t("button.password_format")),
  })
);

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

watch(
  () => props.formState,
  (newValue) => {
    console.log("formState: ", newValue);
    let newSchema;
    if (Boolean(newValue?.Id)) {
      newSchema = yup.object({
        Account: yup.string().required(t("button.required")),
        Name: yup.string().required(t("button.required")),
        Email: yup
          .string()
          .email(t("button.email_format"))
          .required(t("button.required")),
        Phone: yup
          .string()
          .phone("TW", t("button.phone_format"))
          .required(t("button.required")),
        RoleId: yup.string().required(t("button.required")),
        Password: yup.string(),
      });
    } else {
      newSchema = yup.object({
        Account: yup.string().required(t("button.required")),
        Name: yup.string().required(t("button.required")),
        Email: yup
          .string()
          .email(t("button.email_format"))
          .required(t("button.required")),
        Phone: yup
          .string()
          .phone("TW", t("button.phone_format"))
          .required(t("button.required")),
        RoleId: yup.string().required(t("button.required")),
        Password: yup
          .string()
          .required(t("button.required"))
          .matches(
            /^(?=.{8})(?=.*[A-Za-z])(?=.*\d)/g,
            t("button.password_format")
          ),
      });
    }
    userSchema.value = newSchema;
    updateScheme(newSchema);
  }
);

const roleList = ref([]);

const getRole = async () => {
  const res = await getAccountRoleList();
  roleList.value = res.data.map((d) => ({
    ...d,
    key: d.role_guid,
    value: d.role_guid,
  }));
};

onMounted(() => {
  getRole();
});

const onCancel = () => {
  props.reset();
  handleErrorReset();
  account_user_modal.close();
};

const onOk = async () => {
  console.log(userSchema.value);
  const value = await handleSubmit(userSchema.value, props.formState);
  const res = await postAccountUser(value);
  if (res.isSuccess) {
    props.getData();
    onCancel();
  } else {
    openToast("error", res.msg, "#account_user_modal");
  }
};
</script>

<template>
  <Modal
    id="account_user_modal"
    :title="formState?.Id ? t('button.edit') : t('button.add')"
    :onCancel="onCancel"
    width="710"
  >
    <template #modalContent>
      <form ref="form" class="mt-5 w-full flex flex-wrap justify-between">
        <Input
          :value="formState"
          class="my-2"
          name="Account"
          :disabled="Boolean(formState?.Id)"
        >
          <template #topLeft>{{ $t("accountManagement.account") }}</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ formErrorMsg.Account }}
            </span></template
          ></Input
        >
        <Input
          v-if="!Boolean(formState?.Id)"
          :value="formState"
          class="relative my-2"
          name="Password"
          :type="showPassword ? 'text' : 'password'"
        >
          <template #topLeft>{{ $t("accountManagement.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>
        <Input :value="formState" class="my-2" name="Name">
          <template #topLeft>{{ $t("accountManagement.name") }}</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ formErrorMsg.Name }}
            </span></template
          >
        </Input>

        <Input class="my-2" :value="formState" name="Email">
          <template #topLeft>{{ $t("accountManagement.email") }}</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ formErrorMsg.Email }}
            </span></template
          >
        </Input>
        <Input class="my-2" :value="formState" name="Phone">
          <template #topLeft>{{ $t("accountManagement.phone") }}</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ formErrorMsg.Phone }}
            </span></template
          >
        </Input>

        <Select
          :value="formState"
          class="my-2"
          selectClass="border-info  focus-within:border-info"
          name="RoleId"
          Attribute="full_name"
          :options="roleList"
        >
          <template #topLeft>{{
            $t("accountManagement.role_permissions")
          }}</template>
          <template #bottomLeft
            ><span class="text-error text-base">
              {{ formErrorMsg.RoleId }}
            </span></template
          >
        </Select>
      </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>
