<template>
  <div>
    <div class="row justify-content-center">
      <div class="col-12 col-lg-9 col-md-11 col-sm-12 col-xl-8">
        <h1 class="h3 fw-bold text-center py-3">
          <span class="float-start" style="cursor: pointer" @click="$router.go(-1)"><i class="fa-solid fa-arrow-left-long" /></span>
          {{ t("Edit Account") }}
        </h1>
        <div class="row pt-4">
          <div class="col-12">
            <form @submit.prevent="validateAndSave">
              <div class="row">
                <div class="col-12">
                  <label for="firstname" class="text-muted ">{{ t("First Name") }} </label>
                  <input id="firstname" v-model="form.first_name" type="text" class="form-control" :placeholder="t('First Name')">
                  <div v-if="errors.first_name" class="invalid-feedback d-block">
                    {{ errors.first_name[0] }}
                  </div>
                </div>
              </div>
              <div class="row pt-3">
                <div class="col-12">
                  <label for="surname" class="text-muted ">{{ t("Surname") }} </label>
                  <input id="surname" v-model="form.surname" type="text" class="form-control" :placeholder="t('Surname')">
                  <div v-if="errors.surname" class="invalid-feedback d-block">
                    {{ errors.surname[0] }}
                  </div>
                </div>
              </div>
              <div class="row pt-3">
                <div class="col-12">
                  <label for="email" class="text-muted ">{{ t("Email") }} </label>
                  <input id="email" v-model="form.email" type="email" class="form-control" :placeholder="t('Email')">
                  <div v-if="errors.email" class="invalid-feedback d-block">
                    {{ errors.email[0] }}
                  </div>
                </div>
              </div>

              <div class="row pt-3">
                <div class="col-12 col-sm-6">
                  <label for="password" class="text-muted ">{{ t("Password") }} </label>
                  <input id="password" v-model="form.password" type="password" class="form-control" placeholder="***">
                  <div v-if="errors.password" class="invalid-feedback d-block">
                    {{ errors.password[0] }}
                  </div>
                </div>
                <div class="col-12 col-sm-6">
                  <label for="confirm-password" class="text-muted ">{{ t("Confirm Password") }} </label>
                  <input id="confirm-password" v-model="form.confirm_password" type="password" class="form-control" placeholder="***">
                  <div v-if="errors.confirm_password" class="invalid-feedback d-block">
                    {{ errors.confirm_password[0] }}
                  </div>
                </div>
              </div>
              <div class="row pt-3">
                <div class="col-12">
                  <label for="language" class="text-muted ">{{ t("Language") }} </label>
                  <select id="language" v-model="form.language" class="form-select" @change="changeLanguage">
                    <option value="en">
                      English
                    </option>
                    <option value="de">
                      German
                    </option>
                  </select>
                  <div v-if="errors.language" class="invalid-feedback d-block">
                    {{ errors.language[0] }}
                  </div>
                </div>
              </div>
              <div class="row pt-5 g-2">
                <button type="submit" class="btn btn-primary-custom mx-auto col-4" style="background-color: #e9c046">
                  {{ t("Save Changes") }}  <div v-if="loading" class="spinner-border spinner-border-sm" role="status">
                    <span class="sr-only">{{ t("Loading...") }} </span>
                  </div>
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'pinia'
// import Index from '~/pages/index.vue'
import { useUserStore } from '~/stores/user'
export default {
  name: 'EditAccount',
  components: {
    // Index
  },

  setup () {
    const { t } = useI18n()
    const localePath = useLocalePath()
    const switchLocalePath = useSwitchLocalePath()
    const changeLanguage = (locale) => {
      // useNuxtApp().$logger.log('switch', locale)
      useRouter().push(switchLocalePath(locale))

      // i18n.global.locale.value=
    }
    return { t, localePath, changeLanguage }
  },
  data () {
    return {
      loading: false,
      form: {
        first_name: '',
        surname: '',
        email: 'email',
        password: '',
        confirm_password: '',
        language: 'de'
      },
      errors: []
    }
  },

  computed: {
    ...mapState(useUserStore, ['user'])
  },
  mounted () {
    this.form.first_name = this.user.first_name
    this.form.email = this.user.email
    this.form.surname = this.user.surname
    this.form.language = this.user.language
  },
  methods: {

    ...mapActions(useUserStore, ['updateUser']),

    validateAndSave () {
      this.errors = []

      // Wenn Passwort leer ist, lassen wir die Prüfung zu – Änderung des Passworts ist optional
      if (this.form.password !== '') {
        if (this.form.password !== this.form.confirm_password) {
          this.errors.confirm_password = ['Passwörter stimmen nicht überein.']
          return
        }
      }

      this.saveUser()
    },
    saveUser () {
      this.loading = true

      const payload = { ...this.form }
      if (!payload.password) { delete payload.password }
      if (!payload.confirm_password) { delete payload.confirm_password }

      this.$axios.post('/api/account/update', payload).then(({ data }) => {
        this.changeLanguage(this.form.language)
        this.loading = false
        if (data.success) {
          this.$toast.success(data.message)
          this.updateUser(data.user)
          this.$router.push(this.localePath('/settings/account'))
        }
      }).catch((error) => {
        this.loading = false
        this.$toast.error('Something wrong while saving...')
        if (error.response.status === 422) {
          this.errors = error.response.data.errors
        }
      })
    }
  }
}
</script>
