<template>
  <div class="sign-up__form">
    <div class="sign-up__form-inputs">
      <!--Add  error-input to its class for error-->
      <div class="sign-up__form-row sign-up__simple-input">
        <div
          class="form-group position-relative"
          :class="{ 'form-group--error': v$.name.$error }"
        >
          <input
            class="form-control elem__placeholder-gray"
            v-model.trim="name"
            type="text"
            :placeholder="$t('Name')"
            name="name"
            id="name"
            autocomplete="off"
          />
        </div>
        <div v-if="submitStatus === 'ERROR'">
          <div class="error" v-if="!v$.name.required">
            {{ $t("IsRequired") }}
          </div>
        </div>
      </div>
      <div class="sign-up__form-row sign-up__simple-input">
        <div
          class="form-group position-relative"
          :class="{ 'form-group--error': v$.last_name.$error }"
        >
          <input
            class="form-control elem__placeholder-gray"
            v-model.trim="last_name"
            type="text"
            :placeholder="$t('LastName')"
            name="last_name"
            id="last_name"
            autocomplete="off"
          />
        </div>
        <div v-if="submitStatus === 'ERROR'">
          <div class="error" v-if="!v$.last_name.required">
            {{ $t("IsRequired") }}
          </div>
        </div>
      </div>
      <div class="sign-up__form-row sign-up__simple-input">
        <div
          class="form-group position-relative"
          :class="{ 'form-group--error': v$.username.$error }"
        >
          <input
            class="form-control elem__placeholder-gray"
            type="text"
            name=""
            id=""
            v-model.trim="username"
            :placeholder="$t('UserName')"
            dir="ltr"
            autocomplete="off"
          />
        </div>
        <div v-if="submitStatus === 'ERROR'">
          <div class="error" v-if="!v$.username.required">
            {{ $t("IsRequired") }}
          </div>
        </div>
      </div>
      <div class="sign-up__form-row sign-up__simple-input">
        <div
          class="form-group position-relative"
          :class="{ 'form-group--error': v$.email.$error }"
        >
          <input
            class="form-control elem__placeholder-gray"
            type="text"
            name=""
            id=""
            v-model.trim="email"
            :placeholder="$t('Email')"
            dir="ltr"
            autocomplete="off"
          />
        </div>
        <div v-if="submitStatus === 'ERROR'">
          <div class="error" v-if="!v$.email.required">
            {{ $t("IsRequired") }}
          </div>
        </div>
      </div>
      <div class="sign-up__form-row sign-up__simple-input">
        <div
          class="form-group position-relative"
          :class="{ 'form-group--error': v$.password.$error }"
        >
          <input
            class="form-control elem__placeholder-gray"
            :type="passwordFieldType"
            name=""
            id=""
            v-model.trim="password"
            :placeholder="$t('Password')"
            dir="ltr"
            autocomplete="off"
            @focus="isFocusedOnPassword = true"
            @blur="isFocusedOnPassword = false"
          />
          <button
            type="button"
            @click="togglePasswordVisibility"
            class="toggle-password-btn"
          >
            <svg v-if="isPasswordVisible" class="icon icon-eye">
              <use xlink:href="#icon-eye"></use>
            </svg>
            <svg v-else class="icon icon-Eye-Slash">
              <use xlink:href="#icon-Eye-Slash"></use>
            </svg>
          </button>
        </div>
        <transition name="fade">
          <div v-if="isFocusedOnPassword" class="password-requirements">
            <ul>
              <li
                :class="{
                  'text-success':
                    !v$.password.$pending && v$.password.minLength,
                  'text-danger': !v$.password.minLength,
                }"
              >
                طول آن حداقل باید 8 کاراکتر باشد
              </li>
              <li
                :class="{
                  'text-success':
                    !v$.password.$pending && v$.password.hasLowerCase,
                  'text-danger': !v$.password.hasLowerCase,
                }"
              >
                حداقل شامل یک حرف کوچک باشد
              </li>
              <li
                :class="{
                  'text-success':
                    !v$.password.$pending && v$.password.hasUpperCase,
                  'text-danger': !v$.password.hasUpperCase,
                }"
              >
                حداقل شامل یک حرف بزرگ باشد
              </li>
              <li
                :class="{
                  'text-success':
                    !v$.password.$pending && v$.password.hasSpecialChar,
                  'text-danger': !v$.password.hasSpecialChar,
                }"
              >
                حداقل شامل یک کاراکتر خاص باشد
              </li>
            </ul>
          </div>
        </transition>

        <div v-if="submitStatus === 'ERROR'">
          <div class="error" v-if="!v$.password.required">
            {{ $t("IsRequired") }}
          </div>
          <div class="error" v-if="!v$.password.minLength">
            {{ $t("passwordMustHaveAtLeast") }}
            {{ v$.password.$params.minLength.min }} {{ $t("Letters") }}
          </div>
        </div>
      </div>
      <div class="sign-up__form-row sign-up__simple-input">
        <div
          class="form-group position-relative"
          :class="{ 'form-group--error': v$.repassword.$error }"
        >
          <input
            class="form-control elem__placeholder-gray m-0"
            type="password"
            name=""
            id=""
            v-model.trim="repassword"
            :placeholder="$t('RepeatThePassword')"
            dir="ltr"
            autocomplete="off"
          />
        </div>
        <div v-if="submitStatus === 'ERROR'">
          <div class="error" v-if="!v$.repassword.required">
            {{ $t("IsRequired") }}
          </div>
          <div class="error" v-if="!v$.repassword.sameAsPassword">
            {{ $t("PasswordsDoNotMatch") }}
          </div>
        </div>
      </div>
    </div>
    <div class="sign-up__form-row sign-up__simple-input">
      <div
        class="form-group position-relative d-flex align-items-center"
        :class="{ 'form-group--error': v$.captcha.$error }"
      >
        <input
          class="form-control elem__placeholder-gray mb-0 flex-grow-1"
          type="text"
          name="captcha"
          v-model.trim="captcha"
          :placeholder="$t('SecurityCode')"
          dir="ltr"
        />
        <div class="d-flex border-1 p-2">
          <div class="captcha-container" style="width: 7em">
            <img
              style="width: 100%; height: 100%; object-fit: contain"
              :src="captchaImage"
              alt=""
            />
          </div>
          <button-component
            style="min-width: auto"
            @click="resetCaptcha"
            classes="border-0"
            buttonText=""
            :buttonLoading="loading"
          >
            <svg style="width: 1.3em" class="icon icon-reset-form">
              <use xlink:href="#icon-reset-form"></use>
            </svg>
          </button-component>
        </div>
      </div>
      <div v-if="submitStatus === 'ERROR'">
        <div class="error" v-if="!v$.captcha.required">
          {{ $t("IsRequired") }}
        </div>
      </div>
    </div>
    <div class="sign-up__btn-container">
      <RouterLink
        v-if="!isMajlesBuild()"
        class="sign-up__text text__gray"
        :to="{ path: '/loginphone' }"
        >{{ $t("LoginWithMobile") }}
      </RouterLink>
      <button v-on:click="authBase('doregister')">
        <the-button-loading v-if="loading"></the-button-loading>
        {{ $t("Register") }}
      </button>
    </div>
  </div>
</template>

<script>
// import { mapActions } from "pinia";
import { useVuelidate } from "@vuelidate/core";
import { required, minLength, sameAs } from "@vuelidate/validators";

import authMixin from "~/mixins/authMixin";
// import apis from "~/apis/authApi";

export default {
  mixins: [authMixin],

  mounted() {
    // const req = await useAPI(apis.captcha, {
    //   baseURL: import.meta.env.VITE_AUTH_BASE_URL,
    //   method: "GET",
    // });

    // if (req.status.value) {
    //   this.captchaImage = `data:image/jpeg; charset=utf-8; base64, ${req.data.value}`;
    // } else {
    //   this.captchaImage = (
    //     await import(`~/assets/common/img/captcha.png`)
    //   ).default;
    // }

    this.getCaptcha()
      .then((res) => {
        this.captchaImage = `data:image/jpeg; charset=utf-8; base64, ${res}`;
      })
      .catch((err) => {
        this.captchaImage = import(`~/assets/common/img/captcha.png`)
      });
  },
  setup() {
    return { v$: useVuelidate() };
  },

  validations() {
    return {
      name: {
        required,
        minLength: minLength(1),
      },
      last_name: {
        required,
        minLength: minLength(1),
      },
      password: {
        required,
        minLength: minLength(8),
        hasLowerCase: (value) => /[a-z]/.test(value),
        hasUpperCase: (value) => /[A-Z]/.test(value),
        hasSpecialChar: (value) => /[!@#$%^&*(),.?":{}|<>]/.test(value),
      },
      repassword: {
        required,
        sameAsPassword: sameAs("password"),
      },
      username: {
        required,
      },
      email: {
        required,
        email: true,
      },
      captcha: {},
    };
  },
  data() {
    return {
      name: null,
      last_name: null,
      username: null,
      email: null,
      password: null,
      repassword: null,
      captcha: undefined,
      isFocusedOnPassword: false,
      isPasswordVisible: true,
      captchaImage: "",
    };
  },
  computed: {
    passwordFieldType() {
      return this.isPasswordVisible ? "text" : "password";
    },
  },
  methods: {
    togglePasswordVisibility() {
      this.isPasswordVisible = !this.isPasswordVisible;
    },
  },
};
</script>

<style>
.toggle-password-btn {
  position: absolute;
  left: 0;
  min-width: 26px !important;
  height: 48px !important;
  border: 0 !important;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  font-size: 16px;
}
.password-requirements {
  /* position: absolute;
  top: 100%;
  left: 0; */
  background-color: #f9f9f9;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.password-requirements ul {
  list-style-type: disc;
  padding-left: 20px;
  margin: 0;
}

.password-requirements li {
  margin-bottom: 5px;
  font-size: 14px;
  color: #333;
}
</style>
