<template>
  <div class="ProfileHeader">
    <h6 class="ProfileHeader__Note">
      {{ $t('profile.myProfile') }}
    </h6>
    <div class="ProfileHeader__Btns">
      <r-btn
        v-if="isLocalCredential"
        type="submit"
        @click="showResetPasswordModal = true"
      >
        <q-icon name="pgs-key" />
        <span>{{ $t('profile.resetPassword') }}</span>
      </r-btn>
      <r-btn
        v-if="$AC.haveScope($AC.scopes.SECURITY_ADMINISTRATOR)"
        type="submit"
        @click="showEditModal = true"
      >
        <q-icon name="pgs-edit" />
        <span>{{ $t('profile.edit') }}</span>
      </r-btn>
    </div>
    <ResetPasswordModal
      :personId="personIdForModal"
      @close="showResetPasswordModal = false"
    />
    <EditModal
      :show-modal="showEditModal"
      :person="person"
      :is-local-credential="isLocalCredential"
      @close="showEditModal = false"
      @refresh="refreshData"
    />
  </div>
</template>

<script lang="ts">
import { Person, PersonApi, LocalCredentialTO } from '@/openapi/idm';
import {
  Component,
  InjectReactive,
  Mixins,
  Watch,
} from 'vue-property-decorator';
import { oidc } from '../utils/mixins';
import { personInjectionKey } from '../utils/keys';
import ResetPasswordModal from './ResetPasswordModal.vue';
import EditModal from './modals/EditModal.vue';

const personApi = new PersonApi();

@Component({
  components: {
    ResetPasswordModal,
    EditModal,
  },
})
export default class ProfileHeader extends Mixins(oidc) {
  @InjectReactive(personInjectionKey) person: Person | null;

  showResetPasswordModal = false;
  credentials: LocalCredentialTO[] = [];
  loadingEditProcess = false;
  showEditModal = false;

  private get isLocalCredential(): boolean {
    const credentials = this.credentials.filter(
      (credential) => credential.schema === 'LocalCredential'
    );
    return !!credentials?.length;
  }

  refreshData(): void {
    this.showEditModal = false;
    this.$emit('reloadDate');
  }

  get personIdForModal(): string {
    // showResetPasswordModal если false то не показываем модальное окно,
    // соответственно делаем строку пустой
    return this.showResetPasswordModal ? this.person?.id || '' : '';
  }

  @Watch('person', { deep: true })
  changePerson(): void {
    if (this.person?.id) {
      personApi.getCredentials(this.person.id).then(({ data: credentials }) => {
        this.credentials = credentials;
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.ProfileHeader {
  padding: 16px;
  background-color: rgba(#357eac, 0.05);
  border-bottom: 1px solid rgba(#014874, 0.11);
  display: flex;
  align-items: center;
  justify-content: space-between;

  &__Note {
    margin: 0;
    font-family: 'Golos Text';
    font-size: 12px;
    font-weight: 600;
    line-height: 16px;
    letter-spacing: 0em;
  }

  &__Btns {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  &__CircleLoader {
    color: #1491cf;
  }
}
</style>
