<template>
  <div class="sign-up__form">
    <!--Add  error-input to its class for error-->
    <div class="sign-up__form-row sign-up__simple-input">
      <div class="form-group position-relative">
        <input
          dir="ltr"
          class="form-control elem__placeholder-gray"
          type="text"
          name="username"
          v-model.trim="username"
          :placeholder="$t('UserNameOrEmail')"
        />
      </div>
      <div v-if="submitStatus === 'ERROR'">
        <div class="error" v-if="v$.username.$error"></div>
        {{ $t("IsRequired") }}
      </div>
    </div>

    <div class="sign-up__form-row sign-up__simple-input">
      <div class="form-group position-relative mb-4">
        <input
          @keyup.enter="authBase('dologin')"
          class="form-control elem__placeholder-gray mb-0"
          type="password"
          name="password"
          v-model.trim="password"
          dir="ltr"
          :placeholder="$t('Password')"
        />
        <div class="sign-up__btn-container">
          <a
            href="رمز خود را فراموش کرده اید"
            @click.prevent="goLoginPhonePage(true)"
            class="sign-up__text text__gray"
            >{{ $t("ForgotYourPassword") }}
          </a>
          <!-- <RouterLink
        tag="a"
        class="sign-up__text text__gray"
        :to="{ path: '/forget' }"
        >رمز خود را فراموش کرده اید
      </RouterLink> -->
        </div>
      </div>
      <div v-if="submitStatus === 'ERROR'">
        <div class="error" v-if="v$.password.$error"></div>
        {{ $t("IsRequired") }}
      </div>
    </div>

    <div class="sign-up__form-row sign-up__simple-input">
      <div class="form-group position-relative d-flex align-items-center">
        <input
          class="form-control elem__placeholder-gray mb-0 flex-grow-1"
          type="text"
          name="captcha"
          v-model.trim="captcha"
          dir="ltr"
          @keyup.enter="authBase('dologin')"
          :placeholder="$t('SecurityCode')"
        />
        <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.$error"></div>
        {{ $t("IsRequired") }}
      </div>
    </div>

    <div class="sign-up__btn-container">
      <a
        v-if="!isMajlesBuild()"
        href="رمز خود را فراموش کرده اید"
        @click.prevent="goLoginPhonePage(false)"
        class="sign-up__text text__gray"
        >{{ $t("LoginWithMobile") }}
      </a>

      <!-- <RouterLink
        tag="a"
        class="sign-up__text text__gray"
        :to="{ path: '/loginphone' }"
        >ورود با شماره تلفن
      </RouterLink> -->

      <button :disabled="loading" v-on:click="authBase('dologin')">
        <the-button-loading v-if="loading"></the-button-loading>
        {{ $t("Login") }}
      </button>
    </div>

    <div class="signup__google elem__google">
      <button-component
        @click="loginGuest"
        classes="btn-block"
        :buttonLoading="loading"
        :buttonText="$t('LoginGuest')"
      >
        <img src="assets/common/img/user.svg" alt="کاربر مهمان" />
      </button-component>

      <!-- <button
        :disabled="loading"
        class="w-100"
        title="ورود به عنوان مهمان"
        @click.prevent="loginGuest"
      >
        <span class="text__gray">ورود به عنوان مهمان</span>
        <img src="assets/common/img/user.svg" alt="کاربر مهمان" />
      </button> -->
    </div>
    <!-- <div class="signup__google elem__google">
              <button class="w-100" disabled href="#" @click.prevent="loginWithGoogle">
                <span class="text__gray">ورود با گوگل</span>
                <img src="img/google.png" alt=""/>
              </button>
            </div> -->
  </div>
</template>

<script lang="ts">
import authMixin from "~/mixins/authMixin";
import { mapActions } from "pinia";
import apis from "~/apis/authApi";
import { useAuthStore } from "~/stores/authStore";
import { useVuelidate } from "@vuelidate/core";
import { required, minLength } from "@vuelidate/validators";

export default {
  setup() {
    return { v$: useVuelidate() };
  },
  mixins: [authMixin],
  async mounted() {
    // mySwalToast({
    //   title: "hello",
    // });
    // mySwalConfirm({
    //   title: "هشدار!!!",
    //   html: `از حذف اطلاعات جاری اطمینان دارید؟ `,
    //   icon: "warning",
    // }).then((result) => {
    //   if (result.isConfirmed) {
    //     this.$emit("delete");
    //   }
    // })
    // this.getCaptcha()
    //   .then((res) => {
    //     this.captchaImage = `data:image/jpeg; charset=utf-8; base64, ${res}`;
    //   })
    //   .catch((err) => {
    //     this.captchaImage = (import(`assets/common/img/captcha.png`)).default;
    //   });

    // data, status and error are Vue refs and they should be accessed with .value
    // when used within the <script setup>, while refresh/execute and clear are
    //  plain functions..
    try {
      // const req = await $fetch(apis.captcha, {
      //   baseURL: import.meta.env.VITE_AUTH_BASE_URL,
      //   method: "GET",
      // });
      // this.captchaImage = `data:image/jpeg; charset=utf-8; base64, ${req}`;

      const { $api } = useNuxtApp();
      const data: resModelThree = await $api(apis.captcha, {
        baseURL: import.meta.env.VITE_AUTH_BASE_URL,
        method: "GET",
      });
      this.captchaImage = `data:image/jpeg; charset=utf-8; base64, ${data}`;
    } catch (err) {
      this.captchaImage = (
        await import(`assets/common/img/captcha.png`)
      ).default;
    }
  },

  // setup() {
  //   const v$ = useVuelidate(this.validations, this, {
  //     $lazy: true, // Example config option
  //     $autoDirty: true,
  //   });
  //   return { v$ };
  // },
  // validationConfig: {
  //   $lazy: true, // Alternative way to set config
  // },

  validations() {
    return {
      password: {
        required,
        $autoDirty: true,
      },
      username: {
        required,
        $autoDirty: true,
      },
      captcha: {
        // required,
      },
    };
  },
  data() {
    return {
      username: null,
      password: null,
      captcha: undefined,
      captchaImage: "",
    };
  },
  methods: {
    ...mapActions(useAuthStore, ["setUser"]),
    // ...mapActions(["SET_IS_RESET_PASSWORD"]),
    // async login() {
    //   try {
    //     const payload = {
    //       username: this.username,
    //       password: this.password,
    //       captcha: this.captcha,
    //     };

    //     const { $api } = useNuxtApp();
    //     const response = await $api(apis.login, {
    //       baseURL: import.meta.env.VITE_AUTH_BASE_URL,
    //       method: "POST",
    //       body: payload,
    //     });

    //     this.setUser(response.data);

    //     navigateTo({
    //       path: "/",
    //     });

    //     // router.push({
    //     //   name: "dashboard",
    //     // });
    //   } catch (error) {
    //     
    //     // this.errors = error?.response?.data.message;
    //     // return error;
    //   }
    //   // const authHttpService = new HttpService(import.meta.env.VITE_AUTH_BASE_URL);

    //   // return new Promise((resolve, reject) => {
    //   //   authHttpService
    //   //     .postRequest(apis.login, credentials)
    //   //     .then((response) => {
    //   //       this.setUser(response.data);
    //   //       resolve(response);
    //   //     })
    //   //     .catch((error) => {
    //   //       this.errors = error?.response?.data.message;
    //   //       reject(error?.response?.data);
    //   //     });
    //   // });
    // },
    goLoginPhonePage(isResetPassword = true): void {
      // this.SET_IS_RESET_PASSWORD(isResetPassword);
      // this.$router.push({
      //   name: "loginphone",
      // });
    },
  },
};
</script>
