<template>
  <div class="profile-password">
    <h2 class="profile-password__title">{{ t('profile.change_password')}}</h2>
    <div class="profile-password__current">
      <UiInput
        v-model="form.currentPassword"
        :label="t('profile.old_password')"
        :placeholder="t('profile.old_password')"
        :error="error.currentPassword"
        type="password"
        hide-label
        autocomplete="new-password"
        @update:error="val => error.currentPassword = val"
      />
    </div>
    <div class="profile-password__new">
      <UiInput
        v-model="form.newPassword"
        :label="t('profile.new_password')"
        :placeholder="t('profile.new_password')"
        :error="error.newPassword"
        type="password"
        hide-label
        autocomplete="new-password"
        @update:error="val => error.newPassword = val"
      />
    </div>
    <UiBtn
      :disabled="loading"
      wide
      size="l"
      class="profile-password__button"
      theme="primary"
      @click="update"
    >{{ t('profile.update') }}</UiBtn>
  </div>
</template>

<script setup lang="ts">
import type { IChangePasswordForm } from '../../types';
import { validatePassword } from '../../runtime';
import { AuthorizationApiService } from '../../services/api/authorization.service';

const form = ref<IChangePasswordForm>({
  newPassword: '',
  currentPassword: '',
});

const { t } = useI18n();

const error = ref({
  currentPassword: false,
  newPassword: false,
});

const loading = ref(false);

function update() {
  error.value.currentPassword = false;
  error.value.newPassword = false;

  if (!validatePassword(form.value.currentPassword)) {
    error.value.currentPassword = true;
  }

  if (!validatePassword(form.value.newPassword)) {
    error.value.newPassword = true;
  }

  if (error.value.currentPassword || error.value.newPassword) {
    return;
  }

  try {
    loading.value = true;
    useUser(AuthorizationApiService).changePassword(form.value);
  } catch(err) {
    console.log(err, 'error password changed');
  } finally {
    loading.value = false;
    form.value.currentPassword = '';
    form.value.newPassword = '';
  }
}
</script>

<style lang="scss">
.profile-password {
  display: grid;
}

.profile-password__title {
  @include font-lg;

  margin-bottom: 24px;
  font-weight: 700;
  text-transform: uppercase;
}

.profile-password__button {
  height: 50px;
}

.profile-password__current {
  margin-bottom: 16px;
}

.profile-password__new {
  margin-bottom: 20px;
}
</style>
