<template>
  <main id="main" style="padding-top: 10px; padding-bottom: 50px;">
    <div class="form">
      <div v-if="boolMessage" class="row">
        <div class="col">
          <alert
            :text="'Register Success! You\'ll be redirected shortly.'"
            :type="'SUCCESS'"
          />
        </div>
      </div>
      <div v-if="boolValidationError" class="row">
        <div class="col">
          <alert :text="errorMessage" :type="errorOccurred" />
        </div>
      </div>
      <h3 class="card-title text-center">User Details</h3>
      <div class="row">
        <div class="col-sm-12 col-md-6">
          <div class="form-group">
            <float-label label="Name" style="width: 100%;">
              <input
                type="text"
                id="inputName"
                class="form-control uniInput my-2"
                v-model="indivUser.name"
                v-bind:class="{
                  'is-valid': indivUser.name,
                  'is-invalid': !requiredField(indivUser.name) && nameLoad,
                }"
                v-on:keyup="nameLoad = true"
                v-on:blur="nameLoad = true"
                placeholder="Name"
              />
              <div class="invalid-feedback">Name is required!</div>
            </float-label>
          </div>
          <div class="form-group">
            <float-label label="Surname" style="width: 100%;">
              <input
                type="text"
                id="inputSurname"
                class="form-control uniInput my-2"
                v-model="indivUser.surname"
                v-bind:class="{
                  'is-valid': indivUser.surname,
                  'is-invalid':
                    !requiredField(indivUser.surname) && surnameLoad,
                }"
                v-on:keyup="surnameLoad = true"
                v-on:blur="surnameLoad = true"
                placeholder="Surname"
              />
              <div class="invalid-feedback">Surname is required!</div>
            </float-label>
          </div>
          <div class="form-group">
            <float-label label="Email" style="width: 100%;">
              <input
                type="email"
                id="inputEmail"
                v-model="indivUser.email"
                class="form-control uniInput my-2"
                v-bind:class="{
                  'is-valid': indivUser.email,
                  'is-invalid': !validEmail(indivUser.email) && emailLoad,
                }"
                v-on:keyup="emailLoad = true"
                v-on:blur="emailLoad = true"
                placeholder="Email"
              />
              <div class="invalid-feedback">
                Valid email address is required!
              </div>
            </float-label>
          </div>
        </div>

        <div class="col-sm-12 col-md-6">
          <div class="form-group">
            <float-label label="Cellphone Number" style="width: 100%;">
              <input
                type="text"
                id="inputCellNumber"
                name="inputCellNumber"
                v-model="indivUser.cellNumber"
                class="form-control uniInput my-2"
                v-bind:class="{
                  'is-valid': indivUser.cellNumber,
                  'is-invalid':
                    !requiredField(indivUser.cellNumber) && cellNumberLoad,
                }"
                v-on:keyup="cellNumberLoad = true"
                v-on:blur="cellNumberLoad = true"
                placeholder="Cellphone Number"
              />
              <div class="invalid-feedback">Cellphone number is required!</div>
            </float-label>
          </div>
          <div class="form-group">
            <float-label label="Landline Number" style="width: 100%;">
              <input
                type="text"
                id="inputTelephone"
                v-model="indivUser.telephone"
                class="form-control uniInput my-2"
                v-bind:class="{ 'is-valid': indivUser.telephone }"
                placeholder="Landline Number"
              />
            </float-label>
          </div>
        </div>
      </div>
      <hr />
      <div class="row">
        <div class="col-sm-12">
          <float-label label="Username" style="width: 100%;">
            <input
              type="text"
              id="inputUsername"
              v-model="indivUser.username"
              class="form-control uniInput my-2"
              v-bind:class="{
                'is-valid': indivUser.username,
                'is-invalid':
                  !requiredField(indivUser.username) && usernameLoad,
              }"
              v-on:keyup="usernameLoad = true"
              v-on:blur="usernameLoad = true"
              placeholder="Username"
            />
            <div class="invalid-feedback">Username is required!</div>
          </float-label>
        </div>
      </div>
      <div class="row">
        <div class="col-sm-12 col-md-6">
          <float-label label="Password" style="width: 100%;">
            <input
              type="password"
              placeholder="Password "
              v-model="indivUser.password"
              id="inputPassword"
              class="form-control uniInput my-2"
              v-bind:class="{
                'is-valid': indivUser.password,
                'is-invalid':
                  !requiredField(indivUser.password) && passwordLoad,
              }"
              v-on:keyup="passwordLoad = true"
              v-on:blur="passwordLoad = true"
            />
            <div class="invalid-feedback">Password is required!</div>
          </float-label>
        </div>
        <div class="col">
          <float-label label="Confirm Password" style="width: 100%;">
            <input
              type="password"
              placeholder="Confirm Password"
              v-model="indivUser.confirmPassword"
              id="inputConfirmPassword"
              class="form-control uniInput my-2"
              v-bind:class="{
                'is-valid': indivUser.confirmPassword,
                'is-invalid':
                  !validConfirm(indivUser.confirmPassword) &&
                  confirmPasswordLoad,
              }"
              v-on:keyup="confirmPasswordLoad = true"
              v-on:blur="confirmPasswordLoad = true"
            />
            <div class="invalid-feedback">
              Password and Confirm password must be the same!
            </div>
          </float-label>
        </div>
      </div>
      <div class="row">
        <div class="col">
          <label for="tc">
            <router-link to="/termsConditionsView">
              Terms & Conditions
            </router-link>
          </label>
          <input name="tc" type="checkbox" class="ml-3 mt-2" v-model="terms" />
        </div>
      </div>
      <button
        v-if="terms"
        class="btn-white-border"
        v-on:click="SubmitData()"
        type="submit"
      >
        SUBMIT
      </button>
      <button
        :data-target="'#myNewUserModal'"
        data-toggle="modal"
        @click="navigate()"
        class="btn-white-border"
        style="float: right;"
        type="submit"
      >
        Cancel
      </button>
      <button
        hidden
        :data-target="'#myModalAgency'"
        data-toggle="modal"
        ref="dataToggle"
      ></button>
    </div>
  </main>
</template>

<script>
/* eslint-disable */
import { mapState, mapActions } from 'vuex'
import carousel from 'vue-owl-carousel'
import alert from '../shared/alert'
import Log from '../../assets/Log'
export default {
  components: {
    carousel,
    alert,
  },
  props: {
    RegisterHeader: { type: String, default: undefined },
  },
  name: 'PrivateIndividual',
  data() {
    return {
      isPasswordShown: 'password',
      selectItems: [{ text: 'password', value: 0 }],
      showPassword: false,
      boolMessage: false,
      terms: false,
      indivUser: {
        name: '',
        surname: '',
        email: '',
        cellNumber: '',
        telephone: '',
        username: '',
        password: '',
        confirmPassword: '',
      },
      boolValidationError: false,
      nameLoad: false,
      surnameLoad: false,
      emailLoad: false,
      cellNumberLoad: false,
      telephoneLoad: false,
      usernameLoad: false,
      passwordLoad: false,
      confirmPasswordLoad: false,
      errorOccurred: '',
      errorMessage: '',
    }
  },
  computed: {
    ...mapState('register', ['registerIndividual']),
    Header() {
      return this.RegisterHeader
        ? 'Agency Administrator Details'
        : 'Private Individual'
    },
  },
  methods: {
    ...mapActions('register', [
      'getIndividual',
      'saveIndividual',
      'updateIndividual',
      'clearIndividual',
    ]),
    navigate() {
      if (Log.getUser().role !== 'Super Admin') {
        this.$router.push('/user/login')
      }
    },
    togglePassword() {
      this.showPassword = true
      this.isPasswordShown = 'text'
    },
    passwordToggled() {
      this.showPassword = false
      this.isPasswordShown = 'password'
    },
    SubmitData() {
      this.indivUser.acceptedTerms = this.terms
      if (this.validatePage()) {
        this.saveIndividual(this.indivUser)
          .then((res) => {
            this.boolMessage = true
            setTimeout(() => {
              if (Log.getUser().role !== 'Super Admin') {
                this.$router.push('/user/login')
              } else {
                this.$refs.dataToggle.click()
                this.$router.go()
              }
            }, 500)
          })
          .catch((err) => {
            console.log(err)
            this.boolValidationError = true
            this.errorOccurred = 'ERROR'
            this.errorMessage = 'Server Error: CONNECTION_REFUSED'
            if (err) {
              if (err.data.message) {
                this.errorMessage = err.data.message
              } else {
                this.errorMessage = 'Error.'
              }
            }
          })
      }
    },
    Close() {
      this.$router.push('/user/login')
    },
    validatePage: function () {
      console.log('validatePage')
      if (
        this.indivUser.name &&
        this.indivUser.surname &&
        this.indivUser.email &&
        this.indivUser.cellNumber &&
        this.indivUser.username &&
        this.indivUser.password &&
        this.indivUser.password === this.indivUser.confirmPassword
      ) {
        this.errorOccurred = ''
        this.errorMessage = ''
        this.boolValidationError = false
        return true
      } else {
        this.boolValidationError = true
        ;(this.nameLoad = true),
          (this.surnameLoad = true),
          (this.emailLoad = true),
          (this.cellNumberLoad = true),
          (this.telephoneLoad = true),
          (this.usernameLoad = true),
          (this.passwordLoad = true),
          (this.confirmPasswordLoad = true),
          (this.errorOccurred = 'ERROR')
        this.errorMessage = 'Please check form and correct all input fields!'
        return false
      }
    },
    requiredField: function (tfield) {
      if (tfield) {
        return true
      } else {
        return false
      }
    },
    validEmail: function (email) {
      var re = /(.+)@(.+){2,}\.(.+){2,}/
      if (email) {
        return re.test(email.toLowerCase())
      } else {
        return re.test(email)
      }
    },
    validConfirm: function (tfield) {
      if (this.requiredField(tfield)) {
        if (tfield === this.indivUser.password) {
          return true
        } else {
          return false
        }
      } else {
        return false
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.btn-disabled {
  font-family: 'Muli';
  font-size: 15px;
  letter-spacing: 1px;
  display: inline-block;
  padding: 10px 32px;
  border-radius: 2px;
  transition: 0.5s;
  margin: 10px;
  color: #fff;
  background: grey;
  border-color: black;
  color: black;
  cursor: not-allowed;
}
.btn-disabled :hover {
  background: grey;
  border-color: black;
  color: black;
  cursor: not-allowed;
}
</style>
