<template>
  <div>

    <q-btn class="color-icons" flat icon="edit" round size="md" @click="showDialog = true">
      <q-tooltip class="bg-primary text-white">Изменить</q-tooltip>
    </q-btn>
    <q-dialog v-model="showDialog" :maximized="!$q.screen.gt.xs" persistent width="380">
      <q-card :dark="dark" flat class="main-block-with-cropped relative-position">
        <q-btn class="absolute-top-right z-top" flat dense color="red" icon="close" label="" v-close-popup
          @click="step === 3 ? onReset() : null" />
        <q-card-section horizontal>
          <q-item :dark="dark">
            <q-item-section>
              <q-item-label class="text-h6">Изменение адреса электронной почты</q-item-label>
            </q-item-section>
          </q-item>
        </q-card-section>
        <q-card-section>
          <q-stepper ref="stepper" v-model="step" :contracted="!$q.screen.gt.xs" :dark="dark" animated color="primary"
            flat vertical class="bg-transparent">
            <q-step :dark="dark" :done="step > 1" :name="1" :step="1" :title="steps[0].text" icon="settings">
              <q-input ref="email" v-model="newEmail" :dark="dark" :rules="emailRules" label="Адрес электронной почты"
                outlined></q-input>
            </q-step>
            <q-step :name="2" :step="2" :title="steps[1].text" icon="settings">
              <q-input v-model="confirmCode" :dark="dark" label="Код подтверждения" outlined></q-input>
            </q-step>
            <q-step :name="3" :step="3" :title="steps[2].text" icon="settings">
            </q-step>
            <template v-slot:navigation>
              <q-stepper-navigation>
                <div class="row justify-end" v-if="step < 3">
                  <q-btn outline color="primary" @click="step === 1 ? sendCode() : sendConfirmCode()">
                    <template v-slot:default>
                      <div class="flex no-wrap">
                        <span>{{
                          step === 1
                          ? "Изменить почту"
                          : "Отправить код подтверждения"
                        }}</span>
                        <q-icon v-if="!progress" style="margin-left: 0.25rem" color="primary" name="send"></q-icon>
                        <q-circular-progress v-else style="margin-left: 0.25rem" indeterminate size="28" />
                      </div>
                    </template>
                  </q-btn>
                </div>
              </q-stepper-navigation>
            </template>
            <template v-slot:message>
              <q-banner v-if="step === 1" :dark="dark" class="q-px-lg bg-transparent">
                Введите новый адрес и получите код подтверждения
              </q-banner>
              <q-banner v-else-if="step === 2" :dark="dark" class="q-px-lg bg-transparent">
                Введите код подтверждения отправленный на почту
              </q-banner>
              <q-banner v-else :dark="dark" class="q-px-lg bg-transparent">
                Адрес электронной почты успешно изменен.
              </q-banner>
            </template>
            <!--   оставил заготовку, чтоб можно было двигаться по шагам регистрации
            произвольно
                   <template v-slot:navigation>
              <q-stepper-navigation>
                <q-btn
                  :label="step === 4 ? 'Finish' : 'Continue'"
                  color="primary"
                  @click="$refs.stepper.next()"
                />
                <q-btn
                  v-if="step > 1"
                  class="q-ml-sm"
                  color="primary"
                  flat
                  label="Back"
                  @click="$refs.stepper.previous()"
                />
              </q-stepper-navigation>
            </template> -->
          </q-stepper>
        </q-card-section>
      </q-card>
    </q-dialog>
  </div>
</template>
<script>
import { useUiStore } from '../stores/UI';
import { useUsersStore } from '../stores/users';
import { mapActions, mapState } from 'pinia';

export default {
  // name: 'ChangeEmailDialog',
  components: {},
  data() {
    return {
      dark: false,
      progress: false,
      showDialog: false,
      steps: [
        { step: 1, text: 'Новый адрес' },
        { step: 2, text: 'Код подтверждения' },
        { step: 3, text: 'Адрес изменён' },
      ],
      step: 1,
      confirmCode: null,
      newEmail: null,
      emailRules: [
        (v) => !!v || 'Поле обязательно для заполнения',
        (v) => /^[^@]+@[^@]+\.[^@]+$/.test(v) || 'Указан некорректный e-mail',
        (v) =>
          !Object.prototype.hasOwnProperty.call(
            this.errors,
            'chefaRetposhto'
          ) || this.errors.chefaRetposhto,
      ],
      errors: {},
    };
  },
  methods: {
    ...mapActions(useUsersStore, ['changeTelephoneOrEmail']),
    sendCode() {
      if (!this.newEmail) return;
      if (!this.$refs.email.validate()) {
        return;
      }
      const params = {
        retposhto: this.newEmail,
      };
      this.progress = true;
      this.changeTelephoneOrEmail(params).then((resp) => {
        if (resp.status) {
          this.$q.notify({
            type: 'positive',
            message: resp.message,
          });
          this.step++;
          this.progress = false;
        } else {
          this.$q.notify({
            type: 'negative',
            message: resp.message,
          });
          this.progress = false;
        }
      });
    },

    sendConfirmCode() {
      if (!this.confirmCode) return;
      const params = {
        retposhto: this.newEmail,
        konfirmaKodo: this.confirmCode,
      };
      this.progress = true;

      this.changeTelephoneOrEmail(params).then((resp) => {
        if (resp.status) {
          this.$q.notify({
            type: 'positive',
            message: message,
          });
          this.step++;
          this.progress = false;
        } else {
          this.$q.notify({
            type: 'negative',
            message: message,
          });
          this.progress = false;
        }
      });
    },

    onReset() {
      this.step = 1;
      this.showDialog = false;
    },
  },
  computed: {
    ...mapState(useUiStore, ['dark']),
  },
};
</script>
<style></style>
