<template>
  <pn-page-template>
    <template #title>
      {{$t('account_change_email__title')}}
    </template>

    <q-stepper
      v-model="step"
      vertical
      color="primary"
      animated
      flat
      class="bg-transparent"
      >
      <q-step
        :name="1"
        :title="$t('account_change_email__current_email')"
        :done="step > 1"
        >
        <q-input
          v-model="login"
          autofocus
          dense
          filled
          :label = "$t('account_change_email__current_email')"
          disable
        />
        <q-stepper-navigation>
          <q-btn
            @click="handleSubmit"
            color="primary"
            :label="$t('continue')"
          />
        </q-stepper-navigation>
      </q-step>

      <q-step
        :name="2"
        :title="$t('account_change_email__confirm_current_email')"
        :done="step > 2"
        >
        <div class="q-pb-md">{{$t('account_change_email__confirm_email_message')}}</div>
        <q-input
          v-model="code"
          dense
          filled
          autofocus
          hide-bottom-space
          :label = "$t('account_change_email__code')"
          num="30"
        />
        <q-stepper-navigation>
          <q-btn
            @click="handleSubmit"
            color="primary"
            :label="$t('continue')"
            :disable="code.length === 0"
          />
          <q-btn
            flat
            @click="step = 1"
            color="primary"
            :label="$t('back')"
            class="q-ml-sm"
          />
        </q-stepper-navigation>
      </q-step>

      <q-step
        :name="3"
        :title="$t('account_change_email__new_email')"
        :done="step > 2"
        >
        <q-input
          v-model="newLogin"
          autofocus
          dense
          filled
          :label = "$t('account_change_email__new_email')"
          :rules="validationRules.email"
          lazy-rules
          no-error-icon
          @focus="($refs.emailInput as typeof QInput)?.resetValidation()"
          ref="emailInput"
        />
        <q-stepper-navigation>
          <q-btn
            @click="handleSubmit"
            color="primary"
            :label="$t('continue')"
            :disabled="!isEmailValid"
          />
          <q-btn
            flat
            @click="step = 2"
            color="primary"
            :label="$t('back')"
            class="q-ml-sm"
          />
        </q-stepper-navigation>
      </q-step>

      <q-step
        :name="4"
        :title="$t('account_change_email__confirm_new_email')"
        :done="step > 3"
        >
        <div class="q-pb-md">{{$t('account_change_email__confirm_email_message')}}</div>
        <q-input
          v-model="newCode"
          dense
          filled
          autofocus
          hide-bottom-space
          :label = "$t('account_change_email__code')"
          num="30"
        />
        <q-stepper-navigation>
          <q-btn
            @click="handleSubmit"
            color="primary"
            :label="$t('continue')"
            :disable="newCode.length === 0"
          />
          <q-btn
            flat
            @click="step = 3"
            color="primary"
            :label="$t('back')"
            class="q-ml-sm"
          />
        </q-stepper-navigation>
      </q-step>

      <q-step
        :name="5"
        :title="$t('account_change_email__set_password')"
        >
        <q-input
          v-model="password"
          dense
          filled
          :label = "$t('account_change_email__password')"
          :type="isPwd ? 'password' : 'text'"
          hide-hint
          :hint="passwordHint"
          :rules="validationRules.password"
          lazy-rules
          no-error-icon
          @focus="($refs.passwordInput as typeof QInput)?.resetValidation()"
          ref="passwordInput"
          >
            <template #append>
              <q-icon
                color="grey-5"
                :name="isPwd ? 'mdi-eye-off-outline' : 'mdi-eye-outline'"
                class="cursor-pointer"
                @click="isPwd = !isPwd"
              />
            </template>
          </q-input>

        <q-stepper-navigation>
          <q-btn
            @click="handleSubmit"
            color="primary"
            :label="$t('account_change_email__finish')"
            :disabled = "!isPasswordValid"
          />
          <q-btn
            flat
            @click="step = 4"
            color="primary"
            :label="$t('back')"
            class="q-ml-sm"
          />
        </q-stepper-navigation>
      </q-step>
    </q-stepper>
    
    <pn-magic-overlay
      v-if="showSuccessOverlay"
      icon="mdi-check-circle-outline"
      message1="account_change_email__ok_message1"
      message2="account_change_email__ok_message2"
      route-name="account"
    />
  </pn-page-template>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue'
  import type { AxiosError } from 'axios'
  import { QInput } from 'quasar'
  import { useAuthStore } from 'stores/auth'
  import { useInputRules } from 'composables/useInputRules'

  const { inputRules } = useInputRules()
  const authStore = useAuthStore()

  type Step = 1 | 2 | 3 | 4 | 5

  const step = ref<Step>(1)
  const login = authStore.customer?.email
  const code = ref<string>('')
  const newLogin = ref<string>('')
  const newCode = ref<string>('')
  const password = ref<string>('')
  const showSuccessOverlay = ref(false)
  const isPwd = ref<boolean>(true)
  const validationRules = {
    email: [inputRules.email],
    password: [inputRules.password]
  }

  const isEmailValid = computed(() => 
    validationRules.email.every(f => f(newLogin.value) === true)
  )

  const isPasswordValid = computed(() => 
    validationRules.password.every(f => f(password.value) === true)
  )

  const passwordHint = computed(() => {
    const result = validationRules.password[0] ? validationRules.password[0](password.value) : null
    return typeof result === 'string' ? result : ''
  })

  const stepActions: Record<Step, () => Promise<void>> = {
    1: async () => {
      await authStore.getCodeCurrentEmail()
    },
    2: async () => {
      await authStore.confirmCurrentEmailCode(code.value)
    },
    3: async () => {
      await authStore.getCodeNewEmail(code.value, newLogin.value)
    },
    4: async () => {
      await authStore.confirmNewEmailCode(code.value, newCode.value, newLogin.value,)
    },
    5: async () => {
      await authStore.setNewEmailPassword(code.value, newCode.value, newLogin.value, password.value)
      await authStore.loginWithCredentials(newLogin.value, password.value)
    }
  }

  const handleSubmit = async () => {
    try {
      await stepActions[step.value]()
      if (step.value < 5) {
        step.value++
      } else {
        showSuccessOverlay.value = true
      }
    } catch (error) {
     console.error(error as AxiosError)
    }
  }

</script>
