<template>
  <base-modal
    :show-modal="showModal"
    max-width="600px"
    @close-modal="closeModal">

    <template slot="title">
      Edit Profile Information
    </template>

    <template slot="content">
      <v-container grid-list-md text-xs-left class="edit-profile-modal">
        <v-layout wrap>

          <v-layout row xs12 mb-4 ml-1>
            <v-flex xs2>
              <v-avatar size="56px" class="nav-profile">
                <a href="https://en.gravatar.com/support/activating-your-account/" target="_blank">
                  <img
                    :src="user.picture"
                    alt="Avatar">
                </a>
              </v-avatar>
            </v-flex>
            <v-flex xs10>
              <span class="body-1">
                To add/update a profile Picture, create an account and upload a new picture in
                <a href="https://en.gravatar.com/support/activating-your-account/" target="_blank">www.gravatar.com</a>
                using your email (<b>{{ $get(user, 'email') }}</b>)
              </span>
            </v-flex>
          </v-layout>

          <v-flex xs12>
            <base-editable-field
              :model="user"
              :rules="[rules.required]"
              :loading="loading"
              name="First Name"
              field="first_name"
              @update-value="updateValue"/>
          </v-flex>

          <v-flex xs12>
            <base-editable-field
              :model="user"
              :rules="[rules.required]"
              :loading="loading"
              name="Last Name"
              field="last_name"
              @update-value="updateValue"/>
          </v-flex>

          <v-flex xs12>
            <base-static-field
              :model="user"
              name="Username"
              field="username"/>
          </v-flex>

          <v-flex xs12>
            <base-static-field
              :model="user"
              name="Email"
              field="email"/>
          </v-flex>

          <div class="active-link body-1 primary--text mt-3 mb-3" @click="toggleChangePasswordForm">change password?</div>

          <transition name="slide-y-transition">
            <v-flex v-if="changePasswordVisibility" xs12>
              <v-form
                ref="form"
                lazy-validation>

                <v-text-field
                  ref="old_password"
                  v-model="password.old_password"
                  :rules="[rules.required]"
                  :error-messages="errorMessages.old_password"
                  type="password"
                  label="Current Password"
                  @keyup.enter="changePassword"/>

                <v-text-field
                  ref="new_password1"
                  v-model="password.new_password1"
                  :append-icon="showPassword ? 'visibility_off' : 'visibility'"
                  :rules="[rules.required, rules.min6]"
                  :error-messages="errorMessages.new_password1"
                  :type="showPassword ? 'text' : 'password'"
                  label="Confirm Password"
                  @click:append="showPassword = !showPassword"
                  @keyup.enter="changePassword"/>

                <v-text-field
                  ref="new_password2"
                  v-model="password.new_password2"
                  :rules="[rules.required, validatePassword]"
                  :error-messages="errorMessages.new_password2"
                  type="password"
                  label="Confirm New Password"
                  @keyup.enter="changePassword"/>
              </v-form>
            </v-flex>
          </transition>

        </v-layout>
      </v-container>
    </template>

    <template slot="cancel-btn">
      <div />
    </template>

    <template slot="footer-actions">
      <v-btn
        v-if="changePasswordVisibility"
        class="password-loading"
        color="primary darken-1"
        flat="flat"
        @click="changePassword">
        <v-progress-circular
          v-if="loading"
          :width="3"
          :size="20"
          indeterminate
          color="primary"/>
        <span v-else>Update Password</span>
      </v-btn>
      <v-btn
        flat="flat"
        data-test="clear"
        @click="closeModal">
        Close
      </v-btn>
    </template>

  </base-modal>
</template>

<script>
import BaseModal from '@/components/base/BaseModal.vue'
import BaseEditableField from '@/components/base/BaseEditableField'
import BaseStaticField from '@/components/base/BaseStaticField'

import rules from '@/utils/rules'
import { updateUserProfile, changePassword } from '@/utils/api'
import { USER_SUCCESS } from '@/store/actions/user'
import { SHOW_ALERT } from '@/store/actions/alert'
import { mapGetters } from 'vuex'

export default {
  name: 'EditProfileModal',
  components: {
    BaseModal,
    BaseEditableField,
    BaseStaticField
  },
  props: {
    showModal: {
      type: Boolean,
      default: false,
      required: true
    }
  },
  data () {
    return {
      rules,
      loading: false,
      password: {},
      showPassword: false,
      errorMessages: {},
      changePasswordVisibility: false
    }
  },
  computed: {
    ...mapGetters({
      user: 'getProfile'
    })
  },
  methods: {
    updateValue (data) {
      if (Object.keys(data).length) {
        const user = {
          ...this.user,
          ...data
        }
        this.loading = true
        updateUserProfile(user)
          .then(response => {
            this.$store.commit(USER_SUCCESS, response)
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    changePassword () {
      if (this.$refs.form.validate()) {
        this.loading = true
        changePassword(this.password)
          .then(response => {
            this.$store.dispatch(SHOW_ALERT, {
              message: response.detail
            })
            this.clear()
            this.closeModal()
          })
          .catch(error => {
            this.errorMessages = error
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    validatePassword (value) {
      return this.password.new_password1 === value || "New passwords don't match."
    },
    clear () {
      this.$refs.form.reset()
    },
    closeModal () {
      this.$emit('close-modal')
    },
    toggleChangePasswordForm () {
      this.changePasswordVisibility = !this.changePasswordVisibility
    }
  }
}
</script>

<style lang="scss">
.edit-profile-modal {
  font-size: 16px;
  .base-editable-field,
  .non-base-editable-field,
  .static-field {
    font-size: 16px;
    margin-left: 0px;
  }
}
.nav-profile a {
  height: 56px;
  width: 56px;
}
.password-loading.v-btn .v-btn__content{
  min-width: 130px;
}
</style>
