<template>
  <q-page class="flex flex-center">
    <q-card style="width:420px; max-width:90vw">

      <q-card-section>
        <div class="text-h6 text-weight-bold">🔐 Şifre Değiştir</div>
        <div class="text-caption text-grey-7">
          Mevcut şifrenizi girerek yeni şifre belirleyin
        </div>
      </q-card-section>

      <q-separator />

      <q-form @submit.prevent="submit">
        <q-card-section class="q-gutter-sm">
          <q-input
            v-model="current"
            type="password"
            label="Mevcut Şifre"
            dense filled
          />

          <q-input
            v-model="password"
            type="password"
            label="Yeni Şifre"
            dense filled
          />

          <q-input
            v-model="password2"
            type="password"
            label="Yeni Şifre (Tekrar)"
            dense filled
          />

          <q-banner
            v-if="error"
            class="bg-red-1 text-red q-mt-sm"
            rounded
          >
            {{ error }}
          </q-banner>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn
            type="submit"
            label="GÜNCELLE"
            color="primary"
            :loading="loading"
            :disable="!canSubmit"
          />
        </q-card-actions>
      </q-form>

    </q-card>
  </q-page>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useQuasar } from 'quasar'
import { useMePasswordStore } from 'stores/mePasswordStore'

const $q = useQuasar()
const store = useMePasswordStore()

const current = ref('')
const password = ref('')
const password2 = ref('')
const error = ref(null)

const loading = computed(() => store.loading)

const canSubmit = computed(() =>
  current.value &&
  password.value.length >= 8 &&
  password.value === password2.value &&
  !loading.value
)

async function submit () {
  error.value = null

  if (!canSubmit.value) return

  try {
    await store.changePassword(current.value, password.value)

    $q.notify({
      type: 'positive',
      message: 'Şifre başarıyla güncellendi',
      position: 'top-right'
    })

    current.value = password.value = password2.value = ''
  } catch {
    error.value = store.error
  }
}
</script>
