<template>
  <q-page class="q-pa-sm">
    <q-card class="" bordered flat>
      <q-card-section class="text-h6">
        <div class="text-h6">Редактировать профиль</div>
        <div class="text-subtitle2">Заполните свой профиль</div>
      </q-card-section>
      <q-card-section class="q-pa-sm">
        <q-list class="row">
          <q-item class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <q-item-section side>
              <q-avatar size="100px">
                <img :src="avatarUrl" @error="handleError" alt="Your Image">
              </q-avatar>
            </q-item-section>
            <q-item-section>
              <!-- <q-file ref="fileInput" v-model="avatar" accept="image/*" style="display: none"></q-file> -->
              <q-btn outline label="Добавить фото" class="text-capitalize" color="primary" rounded
                style="max-width: 120px" @click="openFileDialog"></q-btn>
            </q-item-section>
          </q-item>


          <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
            <q-item-section>
              <q-input v-model="user_details.user_name" label="Имя пользователя" />



            </q-item-section>
          </q-item>
          <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
            <q-item-section>
              <q-input v-model="user_details.email" readonly label="Адрес электронной почты">
                <template v-slot:default>
                  <change-email-btn class="q-px-sm" />
                </template>
              </q-input>
            </q-item-section>
          </q-item>
          <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
            <q-item-section>
              <q-input type="text" v-model="user_details.first_name" label="Имя" />
            </q-item-section>
          </q-item>
          <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
            <q-item-section>
              <q-input type="text" v-model="user_details.last_name" label="Фамилия" />
            </q-item-section>
          </q-item>
          <!-- <q-item class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <q-item-section>
              <q-input autogrow v-model="user_details.address" label="Адрес" />
            </q-item-section>
          </q-item>
          <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
            <q-item-section>
              <q-input type="city" v-model="user_details.city" label="Город" />
            </q-item-section>
          </q-item>
          <q-item class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
            <q-item-section>
              <q-input v-model="user_details.post_code" label="Почтовый индекс" />
            </q-item-section>
          </q-item> -->
          <q-item class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <q-item-section>
              <q-input type="textarea" v-model="user_details.about" label="обо мне" />
            </q-item-section>
          </q-item>
        </q-list>
      </q-card-section>
      <q-card-actions align="right">
        <q-btn class="text-capitalize" outline color="primary" @click="updateUser">Обновить информацию
          пользователя</q-btn>
      </q-card-actions>
    </q-card>
    <q-card class="q-mt-sm" bordered flat>
      <q-card-section class="text-h6 q-pa-sm">
        <div class="text-h6">Изменить пароль</div>
      </q-card-section>
      <q-form @submit="onChangePassword">
        <q-card-section class="q-pa-sm row">
          <q-item class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
            <q-item-section>
              Текущий пароль
            </q-item-section>
          </q-item>
          <q-item class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
            <q-item-section>
              <q-input type="password" outlined color="primary" round v-model="currentPassword"
                :rules="currentPasswordRules" label="Текущий пароль" />
            </q-item-section>
          </q-item>
          <q-item class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
            <q-item-section>
              Новый пароль
            </q-item-section>
          </q-item>
          <q-item class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
            <q-item-section>
              <q-input type="password" outlined color="primary" round v-model="newPassword" :rules="newPasswordRules"
                label="Новый пароль" />
            </q-item-section>
          </q-item>
          <q-item class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
            <q-item-section>
              Подтвердить новый пароль
            </q-item-section>
          </q-item>
          <q-item class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
            <q-item-section>
              <q-input type="password" outlined round color="primary" v-model="confirmPassword"
                :rules="confirmPasswordRules" label="Подтвердить новый пароль" />
            </q-item-section>
          </q-item>
        </q-card-section>
        <q-card-actions align="right">
          <q-btn type="submit" class="text-capitalize" outline color="primary">Изменить пароль</q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-page>
</template>

<script >

import { defineComponent } from 'vue';
import { useUsersStore } from 'src/stores/users';
import { mapActions, mapState } from 'pinia';
import { useCurrentUserStore } from '../stores/current-user';
import ChangeEmailBtn from '../components/ChangeEmailDialog';

export default defineComponent({
  data() {
    return {
      user_details: {
        first_name: '',
        user_name: '',
        last_name: '',
        // city: '',
        email: '',
        about: '',
      },

      currentPassword: '',
      newPassword: null,
      confirmPassword: null,
      currentPasswordRules: [
        v => !!v || 'Текущий пароль обязателен',
        v => /^[0-9a-zA-Z+-_*.,;$!?%#=()]+$/.test(v) || 'Недопустимые символы в пароле'
      ],
      newPasswordRules: [
        v => !!v || 'Новый пароль обязателен',
        v => /^[0-9a-zA-Z+-_*.,;$!?%#=()]+$/.test(v) || 'Недопустимые символы в пароле',
        v => (v && v.length >= 6 && v.length <= 32) || 'Длина пароля должна быть от 6 до 32 символов'
      ],
      confirmPasswordRules: [
        v => !!v || 'Подтверждение пароля обязательно',
        v => v === this.newPassword || 'Пароли не совпадают'
      ],
    };
  },

  components: {
    ChangeEmailBtn
  },

  watch: {
    user: {
      handler(val) {
        this.user_details.first_name = val.unuaNomo.enhavo;
        this.user_details.last_name = val.familinomo.enhavo;

      }, immediate: true
    },
    userEmail: {
      handler(val) {
        this.user_details.email = val.chefaRetposhto;

      }, immediate: true
    },
    userAbout: {
      handler(val) {
        this.user_details.about = val.statuso.enhavo;
      }, immediate: true
    },

    userName: {
      handler(val) {
        this.user_details.user_name = val;

      }, immediate: true
    },

    getAvatar: {
      handler(newAvatar) {
        this.avatarUrl = newAvatar;
      }, immediate: true
    }
  },
  computed: {
    ...mapState(useCurrentUserStore, ['getAvatar']),
    ...mapState(useCurrentUserStore, { user: 'getUser' }),
    ...mapState(useCurrentUserStore, { userEmail: 'getUser' }),
    ...mapState(useCurrentUserStore, { userName: 'getUserName' }),
    ...mapState(useCurrentUserStore, { userAbout: 'getUser' })
  },
  methods: {
    onChangePassword() {
      if (this.newPassword !== this.confirmPassword) {
        this.$q.notify({
          color: 'negative',
          message: 'Новый пароль и подтверждение нового пароля не совпадают!'
        });
        return;
      }

      if (this.currentPassword === this.newPassword) {
        this.$q.notify({
          color: 'warning',
          message: 'Новый пароль совпадает с текущим, придумайте новый пароль!'
        });
        return;
      };

      this.changePassword({ pasvorto: this.currentPassword, novaPasvorto: this.newPassword })
        .then(() => {
          this.$q.notify({
            color: 'positive',
            message: 'Пароль успешно изменен!'
          });
          this.currentPassword = '';
          this.newPassword = '';
          this.confirmPassword = '';
        })
        .catch(error => {
          this.$q.notify({
            color: 'negative',
            message: 'Ошибка при изменении пароля: ' + error.message
          });
        });
    },
    ...mapActions(useUsersStore, ['changePassword']),


    openFileDialog() {
      this.$refs.fileInput.$el.click();
    },
    handleError() {
      this.avatarUrl = 'images/noAvatar_1655x1655.png';  // Set the path to your fallback image
    },
    ...mapActions(useUsersStore, ['changeUzanto', 'changeTelephoneNumberOrEmail']),
    ...mapActions(useCurrentUserStore, ['addUniversoUzanto']),

    updateUserName() {
      if (this.userName === this.user_details.user_name) return;

      this.addUniversoUzanto({ retnomo: this.user_details.user_name, uuid: this.user.universoUzanto.uuid })

        .then(() => {
          this.$q.notify({
            color: 'positive',
            message: 'Ваши данные успешно обновлены!'
          });

        })
        .catch(error => {
          this.$q.notify({
            color: 'negative',
            message: 'Ошибка при изменении данных! '
          });
        });

    },



    updateUser() {
      const payload = {};
      if (this.user_details.first_name !== this.user.unuaNomo.enhavo) payload.unuaNomo = this.user_details.first_name;
      if (this.user_details.last_name !== this.user.familinomo.enhavo) payload.familinomo = this.user_details.last_name;
      if (this.user_details.about !== this.user.statuso.enhavo) payload.statuso = this.user_details.about;
      this.updateUserName();

      if (!Object.keys(payload).length) return;
      this.changeUzanto(payload)

        .then(() => {
          this.$q.notify({
            color: 'positive',
            message: 'Ваши данные успешно обновлены!'
          });

        })
        .catch(error => {
          this.$q.notify({
            color: 'negative',
            message: 'Ошибка при изменении данных! '
          });
        });

    },

  },

});
</script>

<style scoped></style>
