<template>
  <div>
    <div v-if="isLoading">
      <base-spinner />
    </div>
    <div class="flex items-center justify-center">
      <div
        class="
          sm:block
          border border-gray-300
          bg-white bg-opacity-60
          rounded-lg
          mt-6
          w-1/3
        "
      >
        <div class="p-5 mx-auto text-left font-raleway">
          <h1
            class="
              font-bold
              text-left
              font-montserrat
              text-3xl
              sm:text-5xl
              mb-7
            "
          >
            Login to CD-Code
          </h1>

          <form @submit="login">
            <div class="my-4" :class="{ invalid: !email.isValid }">
              <h1
                class="
                  text-left
                  font-bold
                  mb-2
                  text-xl
                  sm:text-2xl
                  font-montserrat
                "
              >
                Email*
              </h1>
              <input
                v-model.trim="email.val"
                type="email"
                class="
                  outline-none
                  bg-transparent
                  border border-gray-400
                  px-4
                  py-5
                  rounded-lg
                  w-full
                  hover:border-blue-700
                  focus:border-blue-700
                "
                placeholder="Enter email."
                @blur="clearValidity('email')"
              />
              <p v-if="!email.isValid" class="text-red-500">
                Email must not be empty.
              </p>
            </div>
            <div class="my-4" :class="{ invalid: !password.isValid }">
              <h1
                class="
                  text-left
                  font-bold
                  mb-2
                  text-xl
                  sm:text-2xl
                  font-montserrat
                "
              >
                Password*
              </h1>
              <input
                v-model.trim="password.val"
                type="password"
                class="
                  text-xl
                  outline-none
                  bg-transparent
                  border border-gray-400
                  px-4
                  py-5
                  rounded-lg
                  w-full
                  hover:border-blue-700
                  focus:border-blue-700
                "
                placeholder="Enter password."
                @blur="clearValidity('password')"
              />
              <p v-if="!password.isValid" class="text-red-500">
                Password must not be empty.
              </p>
            </div>
            <p v-show="error" class="text-red-500">
              {{ errorMsg }}
            </p>
            <button
              type="submit"
              class="
                bg-blue-500
                my-4
                text-2xl
                w-full
                font-bold
                rounded-lg
                p-5
                text-white
              "
            >
              Sign in
            </button>
            <p class="my-2 font-bold">
              <router-link
                class="text-pink-base hover:text-pink-base text-2xl"
                to="/forgotpassword"
              >
                Forgot Password?
              </router-link>
            </p>
            <h4>
              Don't have an account yet?
              <router-link
                class="text-pink-base hover:text-pink-base text-2xl font-bold"
                to="/signup"
              >
                Join CD-CODE as a contributor.
              </router-link>
            </h4>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
let host = require("@/components/js/const").apiHost;

export default {
  name: "Login",

  data() {
    return {
      email: {
        val: "",
        isValid: true,
      },
      password: {
        val: "",
        isValid: true,
      },
      formIsValid: true,
      error: false,
      errorMsg: ``,
      isDev: process.env.NODE_ENV === "development",
      isLoading: false,
    };
  },
  computed: {
    userData: function () {
      return this.$store.getters["User/userData"];
    },
  },
  mounted: function () {
    const vm = this;
    if (vm.userData !== null) {
      this.$router.push("/profile");
    }
  },
  methods: {
    clearValidity(input) {
      this[input].isValid = true;
    },
    validateForm() {
      this.formIsValid = true;
      if (this.email.val === "") {
        this.email.isValid = false;
        this.formIsValid = false;
      }
      if (this.password.val === "") {
        this.password.isValid = false;
        this.formIsValid = false;
      }
    },
    async login(e) {
      e.preventDefault();

      const vm = this;
      vm.validateForm();
      if (!vm.formIsValid) {
        return;
      }
      if (vm.isDev) {
        host = require("@/components/js/const").devApiHost;
      }
      console.log("url is", host);
      this.isLoading = true;
      try {
        const res = await fetch(`${host}/api/auth/local`, {
          method: "POST",
          mode: "cors", // no-cors, *cors, same-origin
          cache: "no-cache", // *default, no-cache, reload, force-cache,
          headers: {
            "Content-Type": "application/json",
            // 'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: JSON.stringify({
            identifier: this.email.val,
            password: this.password.val,
          }),
        });

        if (!res.ok) {
          this.isLoading = false;
          this.error = true;
          this.errorMsg = `${res.status} Internal Error, please write a mail to CDCode Admin`;

          return;
        }

        if (!res.ok && res.status === 500) {
          this.isLoading = false;
          this.error = true;
          this.errorMsg = `${res.status} Internal Error, please write a mail to CDCode Admin`;

          return;
        }
        if (!res.ok && res.status === 405) {
          this.isLoading = false;
          this.error = true;
          this.errorMsg = `${res.status} Internal Error, please write a mail to CDCode Admin`;

          return;
        }

        const response = await res.json();
        if (
          !res.ok &&
          response.error.status === 400 &&
          response.error.message === "Invalid identifier or password"
        ) {
          this.isLoading = false;
          this.error = true;
          this.errorMsg = "Email Address & Password mismatch.";
          this.password.val = "";
          return;
        }

        const { jwt, user } = response;

        window.localStorage.setItem("jwt", jwt);
        window.localStorage.setItem("userData", JSON.stringify(user));

        this.$store.dispatch("User/setJwt", jwt);
        this.$store.dispatch("User/setUserData", JSON.stringify(user));
        this.isLoading = false;
        this.error = false;
        this.$router.push("/profile");
      } catch (err) {
        console.log("catch error", err);
        this.isLoading = false;
        this.error = true;
        this.errorMsg = `${err.message} Internal Error, please write a mail to CDCode Admin`;
      }

      // const res = await this.axios.post(`${host}/api/auth/local`, {
      //   identifier: this.email.val,
      //   password: this.password.val
      // });
      // console.log("error is ", res);
      // const { jwt, user } = res.data
      // console.log(user)
      // window.localStorage.setItem('jwt', jwt)
      // window.localStorage.setItem('userData', JSON.stringify(user))

      // this.$store.dispatch('User/setJwt', jwt)
      // this.$store.dispatch('User/setUserData', user)
      // this.isLoading= false;
      // this.error= false;
      // this.$router.push('/profile')

      // console.log(error.response.data.error.message)
      // console.log("error",e.data);
      // this.isLoading= false;
      // this.error = true
      // this.password.val = ''
      // this.isLoading= false
    },
  },
};
</script>
<style scoped>
@import url("~@/assets/bootstrap.css");

/* a {
  color: #ef0087 !important;
} */
.invalid h1 {
  color: red;
}
.invalid input {
  border: 1px solid red;
}
</style>