<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!'" :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">Agency Details</h3>
      <div class="row my-3">
        <div class="col-sm-12 col-md-6">
          <div class="form-group">
            <float-label label="Agency Name" style="width: 100%;">
              <input
                type="text"
                id="inputAgencyName"
                v-model="registerAgency.name"
                class="form-control uniInput"
                v-bind:class="{
                  'is-valid': registerAgency.name,
                  'is-invalid':
                    !requiredField(registerAgency.name) && agencyNameLoad,
                }"
                v-on:keyup="agencyNameLoad = true"
                v-on:blur="agencyNameLoad = true"
                placeholder="Agency Name"
              />
              <div class="invalid-feedback">Agency Name is required!</div>
            </float-label>
          </div>
        </div>
        <div class="col-sm-12 col-md-6">
          <div class="form-group">
            <float-label label="EAAB FFC Number" style="width: 100%;">
              <input
                type="text"
                id="inputAgencyNumber"
                v-model="registerAgency.eaabeffcNumber"
                class="form-control uniInput"
                v-bind:class="{
                  'is-valid': registerAgency.eaabeffcNumber,
                  'is-invalid':
                    !requiredField(registerAgency.eaabeffcNumber) &&
                    agencyNumberLoad,
                }"
                v-on:keyup="agencyNumberLoad = true"
                v-on:blur="agencyNumberLoad = true"
                placeholder="EAAB FFC Number"
              />
              <div class="invalid-feedback">Agency Number is required!</div>
            </float-label>
          </div>
        </div>
      </div>
      <div class="row my-3">
        <div class="col-sm-12">
          <div class="form-group">
            <float-label
              label="Company Registration Number"
              style="width: 100%;"
            >
              <input
                type="text"
                id="inputAgencyCompanyRegistration"
                v-model="registerAgency.companyRegNumber"
                class="form-control uniInput"
                v-bind:class="{
                  'is-valid': registerAgency.companyRegNumber,
                  'is-invalid':
                    !requiredField(registerAgency.companyRegNumber) &&
                    companyRegNumberLoad,
                }"
                v-on:keyup="companyRegNumberLoad = true"
                v-on:blur="companyRegNumberLoad = true"
                placeholder="Company Registration Number"
              />
              <div class="invalid-feedback">
                Company Registration Number is required!
              </div>
            </float-label>
          </div>
        </div>
      </div>
      <h3 class="card-title text-center">Agency Administrator</h3>
      <hr />
      <div class="row my-3">
        <div class="col-sm-12 col-md-6">
          <div class="form-group">
            <float-label label="Name" style="width: 100%;">
              <input
                type="text"
                id="inputAgencyAdmin"
                v-model="registerAgency.user.name"
                class="form-control uniInput my-3"
                v-bind:class="{
                  'is-valid': registerAgency.user.name,
                  'is-invalid':
                    !requiredField(registerAgency.user.name) &&
                    agencyAdminNameLoad,
                }"
                v-on:keyup="agencyAdminNameLoad = true"
                v-on:blur="agencyAdminNameLoad = true"
                placeholder="Name"
              />
              <div class="invalid-feedback">
                Administrator Name is required!
              </div>
            </float-label>
          </div>
          <div class="form-group">
            <float-label label="Surname" style="width: 100%;">
              <input
                type="text"
                id="inputAgencySurname"
                v-model="registerAgency.user.surname"
                class="form-control uniInput my-3"
                v-bind:class="{
                  'is-valid': registerAgency.user.surname,
                  'is-invalid':
                    !requiredField(registerAgency.user.surname) &&
                    agencySurnameLoad,
                }"
                v-on:keyup="agencySurnameLoad = true"
                v-on:blur="agencySurnameLoad = true"
                placeholder="Surname"
              />
              <div class="invalid-feedback">
                Administrator Surname is required!
              </div>
            </float-label>
          </div>
          <div class="form-group">
            <float-label label="Email" style="width: 100%;">
              <input
                type="email"
                id="inputAgencyEmail"
                v-model="registerAgency.user.email"
                v-bind:class="{
                  'is-valid': registerAgency.user.email,
                  'is-invalid':
                    !validEmail(registerAgency.user.email) && agencyEmailLoad,
                }"
                v-on:keyup="agencyEmailLoad = true"
                v-on:blur="agencyEmailLoad = true"
                class="form-control uniInput my-3"
                placeholder="Email"
              />
              <div class="invalid-feedback">Valid email 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="inputAgencyCellphone"
                v-model="registerAgency.user.cellNumber"
                class="form-control uniInput my-3"
                v-bind:class="{
                  'is-valid': registerAgency.user.cellNumber,
                  'is-invalid':
                    !requiredField(
                      validPhoneNumber(registerAgency.user.cellNumber),
                    ) && cellNumberLoad,
                }"
                v-on:keyup="agencyCellNumberLoad = true"
                v-on:blur="agencyCellNumberLoad = true"
                placeholder="Cellphone Number"
              />
              <div class="invalid-feedback">Cell number is required!</div>
            </float-label>
          </div>
          <div class="form-group">
            <float-label label="Landline Number" style="width: 100%;">
              <input
                type="text"
                id="inputAgencyLandLine"
                v-model="registerAgency.user.telephone"
                class="form-control uniInput"
                v-bind:class="{
                  'is-valid':
                    registerAgency.user.telephone &&
                    validPhoneNumber(registerAgency.user.telephone),
                  'is-invalid':
                    registerAgency.user.telephone &&
                    !validPhoneNumber(registerAgency.user.telephone),
                }"
                placeholder="Landline Number"
              />
            </float-label>
          </div>
        </div>
      </div>
      <hr />
      <div class="row my-3">
        <div class="col-sm-12">
          <div class="form-group">
            <float-label label="Username" style="width: 100%;">
              <input
                type="text"
                id="inputAgencyUsername"
                v-model="registerAgency.user.username"
                class="form-control uniInput"
                v-bind:class="{
                  'is-valid': registerAgency.user.username,
                  'is-invalid':
                    !requiredField(registerAgency.user.username) &&
                    agencyusernameLoad,
                }"
                v-on:keyup="agencyusernameLoad = true"
                v-on:blur="agencyusernameLoad = true"
                placeholder="Username"
              />
              <div class="invalid-feedback">Username is required!</div>
            </float-label>
          </div>
        </div>
      </div>
      <div class="row my-3">
        <div class="col-sm-12 col-md-6">
          <div class="form-group">
            <float-label label="Password" style="width: 100%;">
              <input
                type="password"
                placeholder="Password"
                v-model="registerAgency.user.password"
                id="inputAgencyPassword uniInput"
                class="form-control uniInput"
                v-bind:class="{
                  'is-valid': registerAgency.user.password,
                  'is-invalid':
                    !requiredField(registerAgency.user.password) &&
                    agencypasswordLoad,
                }"
                v-on:keyup="agencypasswordLoad = true"
                v-on:blur="agencypasswordLoad = true"
              />
              <div class="invalid-feedback">Password is required!</div>
            </float-label>
          </div>
        </div>
        <div class="col">
          <div class="form-group">
            <float-label label="Confirm Password" style="width: 100%;">
              <input
                type="password"
                placeholder="Confirm Password"
                v-model="registerAgency.user.confirm"
                id="inputAgencyPasswordConfirm"
                class="form-control uniInput"
                v-bind:class="{
                  'is-valid': registerAgency.user.confirm,
                  'is-invalid':
                    !validConfirm(registerAgency.user.confirm) &&
                    agencyconfirmLoad,
                }"
                v-on:keyup="agencyconfirmLoad = true"
                v-on:blur="agencyconfirmLoad = true"
              />
              <div class="invalid-feedback">
                Password and Confirm password must be the same!
              </div>
            </float-label>
          </div>
        </div>
      </div>
      <div class="row">
        <div class="col">
          <label for="agencytc">
            <router-link to="/termsConditionsView">
              Terms & Conditions
            </router-link>
          </label>
          <input
            name="agencytc"
            type="checkbox"
            class="ml-3 mt-2"
            v-model="registerAgency.user.acceptedTerms"
          />
        </div>
      </div>
      <button
        v-if="registerAgency.user.acceptedTerms"
        class="btn-white-border"
        v-on:click="SubmitData()"
        type="submit"
      >
        SUBMIT
      </button>
      <button
        :data-target="'#myModalAgency'"
        data-toggle="modal"
        @click="navigate()"
        class="btn-white-border mb-5"
        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: 'Agency',
  data() {
    return {
      isPasswordShown: 'password',
      selectItems: [{ text: 'password', value: 0 }],
      boolMessage: false,
      boolValidationError: false,
      showPassword: false,
      agencyNameLoad: false,
      agencyNumberLoad: false,
      companyRegNumberLoad: false,
      agencyAdminNameLoad: false,
      agencySurnameLoad: false,
      agencyEmailLoad: false,
      agencyCellNumberLoad: false,
      agencyusernameLoad: false,
      agencypasswordLoad: false,
      agencyconfirmLoad: false,
      errorOccurred: '',
      errorMessage: '',
    }
  },
  computed: {
    ...mapState('register', ['registerAgency']),
    Header() {
      return this.RegisterHeader
        ? 'Agency Administrator Details'
        : 'Private Individual'
    },
  },
  methods: {
    ...mapActions('register', [
      'getAgency',
      'saveAgency',
      'updateAgency',
      'clearAgency',
    ]),
    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.boolValidationError = false
      this.boolMessage = false
      if (this.validatePage()) {
        this.saveAgency(this.registerAgency)
          .then(() => {
            this.boolMessage = true
            console.log('registerAgency true')
            console.log(Log.getUser().role)
            setTimeout(() => {
              if (Log.getUser().role !== 'Super Admin') {
                this.$router.push('/user/login')
              } else {
                this.$refs.dataToggle.click()
                this.$router.go()
              }
            }, 500)
          })
          .catch((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.registerAgency.name &&
        this.registerAgency.eaabeffcNumber &&
        this.registerAgency.companyRegNumber &&
        this.registerAgency.user.name &&
        this.registerAgency.user.surname &&
        this.registerAgency.user.email &&
        this.registerAgency.user.cellNumber &&
        this.registerAgency.user.username &&
        this.registerAgency.user.password &&
        this.registerAgency.user.password ===
          this.registerAgency.user.confirm &&
        this.validEmail(this.registerAgency.user.email) &&
        this.validPhoneNumber(this.registerAgency.user.cellNumber) &&
        this.validPhoneNumber(this.registerAgency.user.telephone)
      ) {
        console.log('passed')
        this.errorOccurred = ''
        this.errorMessage = ''
        this.boolValidationError = true
        return true
      } else {
        console.log('failed')
        this.boolValidationError = true
        ;(this.agencyNameLoad = true),
          (this.agencyNumberLoad = true),
          (this.companyRegNumberLoad = true),
          (this.agencyAdminNameLoad = true),
          (this.agencySurnameLoad = true),
          (this.agencyEmailLoad = true),
          (this.agencyCellNumberLoad = true),
          (this.agencyusernameLoad = true),
          (this.agencypasswordLoad = true),
          (this.agencyconfirmLoad = 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
      }
    },
    validPhoneNumber(number) {
      if (number) {
        const rx = /^\(?\d{3}\)?[-\s]?\d{3}[-\s]?\d{4}$/
        // const rx = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im
        return rx.test(String(number))
      } else {
        return true
      }
    },
    validEmail: function (email) {
      var re = /(.+)@(.+){2,}\.(.+){2,}/
      if (email) {
        return re.test(email.toLowerCase())
      } else {
        return re.test(email)
      }
    },
    validConfirm: function (tfield) {
      //console.log(tfield);
      if (this.requiredField(tfield)) {
        if (tfield === this.registerAgency.user.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>
