<template>
  <div class="w-100 h-100 d-fx fxd-c ai-c pt-48px pr-58px pl-58px pb-69px" v-if="ready">
    <div class="w-120px h-120px d-fx jc-c ai-c o-h">
      <i class="icon-user-circle f-111px c-EAEAEA" v-if="!image_url"></i>
      <img v-else :src="image_url" class="w-100 h-100 bor-50" alt="image">
    </div>
    <!-- form -->
    <form class="w-100 d-fx fxd-c ai-c" @submit.prevent="submit" v-if="$v">
      <h2 class="f-21px lh-27px fw-b c-333333 mt-15px">Sign in to {{siteData}}</h2>
      <div class="w-100 h-52px b-F3F6F6 mt-18px d-fx fxd-c jc-c bor-3px" v-for="(data, key) in login" :key="key">
        <div class="d-fx">
          
        <!-- FIXME fix these icons -->
        <i :class="key === 'email' ? 'icon-mail f-17px w-30px as-c ml-10px mr-5px' : 'icon-lock-empty f-21px as-c ml-10px mr-5px'"></i>
        <input :type="key === 'password' ? 'password' : 'text'" 
          :placeholder="key.charAt(0).toUpperCase() + key.substr(1).toLowerCase()" 
          v-model="login[key]"
          :class="login[key] === '' ? 'c-B1B1B1' : 'c-333333'"
          class="w-100"
          @focus="selectedField = key; $v.login[key].$touch()"
          @blur="selectedField = ''"
          @change="getData(key)">
        </div>
        <div class="">
          <p v-if="$v.login[key].$dirty && !$v.login.email.email && $v.login[key].$model.length > 0 && key === 'email'"
            class="f-9px lh-12px c-FF3030 ml-49px">
            Invalid email
          </p>
          <p v-if="$v.login[key].$dirty && !$v.login.password.authentication && $v.login[key].$model.length > 0 && key === 'password'"
            class="f-9px lh-12px c-FF3030 ml-49px">
            Must contain 4 characters, numbers
          </p>
        </div>
      </div>
      
      <p class="cursor-pointer c-747474 f-14px lh-17px mt-30px" @click="forgotPassword">Forgot your password?</p>
      
      <button type="button" ripple="ripple" class="cursor-pointer xw-201px w-100 h-60px bor-100px mt-35px tn-100ms b-1B1B1B bs-0_6_10_BABABA-H" @click="loginNow"> 
        <span class="f-18px fw-300 lh-60px c-we">SIGN IN</span>
      </button>

    </form>
  </div>
</template>

<script>
import { required, email, minLength } from 'vuelidate/lib/validators'

import { UserM, SignInM } from '@/models/Userist.js'
import {mapStateVModel} from 'map-state-vmodel';

export default {
  name: 'signInC',
  extends: {},
  props: {
    siteData: String,
  },
  data(){
    return{
      ready: false,
      image_url: null,
      login: {
        email: '',
        password: ''
      },
      selectedField: '',
    };
  },
  validations: {
    login: {
      email: {
        required,
        email
      },
      password: {
        authentication (value) {
          return (/^(?=.*?[0-9])(?=.*?[a-z]).{8,}$/.test(value)); // Must contain 4 characters, numbers
          // return (/^(?=.*?[0-9])(?=.*?[A-Z])(?=.*?[a-z]).{8,}$/.test(value));
        },
        minLength: minLength(8),
        required
      }
    }
  },
  components: {},
  computed: {
    ...mapStateVModel('sign', ['user_data', 'sweetAlert_showing']),
  },
  watch: {},
  methods: {
    forgotPassword() {
      this.$swal('Not available for now', '', 'error')
    },
    async getData(key) {
      if (key === 'email') {
        try {
          const { data } = await UserM.getParams({ "email": `${this.login.email}` })
          this.$store.state.sign.user_data = await data.results 
          this.image_url = await data.results[0].image
        } catch (error) {
          this.image_url = null
        }
      } else {
        return false
      }
    },
    async loginNow () { 
      try {
        this.$store.state.ic_loader.loader = await true
        if (this.user_data.length === 1) {
          // console.log(this.user_data);
          let result = await SignInM.getParams({
            "email": `${this.login.email}`,
            "password": `${this.login.password}`
          })
          this.$store.state.auth.id = await result.data.user.id
          this.$store.state.auth.token = await result.data.token.key
          
          await this.$cookies.set("token", result.data.token.key, "7d") // Cookie expiration
          
          // Hiding "sign" and "loader" modals
          this.$store.state.sign.show = await false
          this.$store.state.ic_loader.loader = await false
          
        } else if (this.$v.$error || this.login.password === '' && this.login.email === '') {
          this.$store.state.ic_loader.loader = await false                  
          this.sweetAlert_showing = await true
          await this.$swal('Enter Email and Password', '', 'error')
        } else {
          this.$store.state.ic_loader.loader = await false
          this.sweetAlert_showing = await true
          await this.$swal('Failed to login', 'Email does not exist', 'error')      
        }
      } catch (error) {
        this.$store.state.ic_loader.loader = await false        
        this.sweetAlert_showing = await true
        this.$swal('Failed to login', 'Wrong Password', 'error')
        // console.log(error);
        
      }
    }
  },
  created() { 
    this.ready = true
  },
  beforeCreate(){},
  mounted(){}
}
</script>
