<template>
  <main class="d-flex">
    <span class="mr-2 ot-dark_grey--text font-weight-bold">{{ $t(label) }} : </span>
    <UiXeditableText
      class="activity-year-input"
      type="number"
      :data="activityYear"
      @update="updateActivityYear"
    >
      <template #xeditable.read="{inputValue}">
        <v-icon aria-hidden="false" class="ot-green--text" x-small>
          fas fa-edit
        </v-icon>
        <strong class="ot-green--text"> {{ inputValue }} <span v-if="yearPlusOne">/ {{ parseInt(inputValue) + 1 }}</span></strong>
      </template>
    </UiXeditableText>
  </main>
</template>

<script setup lang="ts">

import {useEntityManager} from "~/composables/data/useEntityManager";
import {useFormStore} from "~/stores/form";
import {useOrganizationProfileStore} from "~/stores/organizationProfile";
import {useAccessProfileStore} from "~/stores/accessProfile";

const { em } = useEntityManager()
const { activityYear } = useAccessProfileStore()
const { isManagerProduct, isSchool, isArtist } = useOrganizationProfileStore()
const { setDirty } = useFormStore()

const setActivityYear = async (activityYear: number) => {
  if (!(1900 < activityYear) || !(activityYear <= 2100)) {
    throw new Error("Error: 'year' shall be a valid year")
  }

  await em.updateProfile({'activityYear': activityYear})
}

const yearPlusOne: boolean = !isManagerProduct
const label: string = isSchool ? 'schooling_year' : isArtist ? 'season_year' : 'cotisation_year'

const updateActivityYear = async (newDate: number) => {
  setDirty(false)
  await setActivityYear(newDate)
  window.location.reload()
}

</script>

<style lang="scss">
  .activity-year-input{
    max-height: 20px;
    input{
      font-size: 14px;
      width: 55px !important;
    }
  }
</style>
