<template>
  <main class="d-flex flex-row align-center">
    <span v-show="mdAndUp" class="mr-2 font-weight-bold on-neutral">
      {{ $t(label) }} :
    </span>

    <UiXeditableText
      class="activity-year-input"
      type="number"
      :data="currentActivityYear"
      @update="setActivityYear"
    >
      <template #xeditable.read="{ inputValue }">
        <div class="d-flex align-center on-neutral--clickable">
          <v-icon
            aria-hidden="false"
            size="small"
            class="mr-1"
            icon="fas fa-edit"
          />
          <strong>
            {{ inputValue }}
            <span v-if="yearPlusOne"> / {{ parseInt(inputValue) + 1 }} </span>
          </strong>
        </div>
      </template>
    </UiXeditableText>
  </main>
</template>

<script setup lang="ts">
import { useDisplay } from 'vuetify'
import { useEntityManager } from '~/composables/data/useEntityManager'
import { useFormStore } from '~/stores/form'
import { useOrganizationProfileStore } from '~/stores/organizationProfile'
import { useAccessProfileStore } from '~/stores/accessProfile'
import Access from '~/models/Access/Access'
import { usePageStore } from '~/stores/page'
import { useRefreshProfile } from '~/composables/data/useRefreshProfile'

const { em } = useEntityManager()
const accessProfileStore = useAccessProfileStore()
const organizationProfileStore = useOrganizationProfileStore()
const formStore = useFormStore()
const pageStore = usePageStore()
const { mdAndUp } = useDisplay()
const { refreshProfile } = useRefreshProfile()

const currentActivityYear: ComputedRef<number | undefined> = computed(
  () => accessProfileStore.activityYear ?? undefined,
)
const yearPlusOne: boolean = !organizationProfileStore.isManagerProduct
const label: string = organizationProfileStore.isSchool
  ? 'schooling_year'
  : organizationProfileStore.isArtist
    ? 'season_year'
    : 'cotisation_year'

/**
 * Persist a new activityYear
 * @param event
 */
const setActivityYear = async (event: string) => {
  const activityYear = parseInt(event)

  if (!(activityYear > 1900) || !(activityYear <= 2100)) {
    throw new Error("Error: 'year' shall be a valid year")
  }
  formStore.setDirty(false)

  pageStore.loading = true
  await em.patch(Access, accessProfileStore.currentAccessId, {
    activityYear,
  })
  if (process.server) {
    // Force profile refresh server side to avoid a bug where server and client stores diverge on profile refresh
    await refreshProfile()
  }

  window.location.reload()
}
</script>

<style lang="scss">
.activity-year-input {
  width: 120px;
  max-height: 20px;

  .v-input {
    min-width: 70px;
  }

  input {
    font-size: 14px;
    width: 55px !important;
    padding: 0 2px 0 6px !important;
    margin-top: 0 !important;
    min-height: 24px;
    height: 24px;
  }
}
</style>
