<!--
Switch year bar

Barre d'alerte qui s'affiche lorsque l'utilisateur n'est pas sur l'année courante.
-->

<template>
  <!-- TODO : fonctionnement à valider -->
  <UiSystemBar v-if="show" class="theme-warning flex-column">
    {{ $t('not_current_year') }}

    <a
      @click="resetYear"
      class="text-decoration-none on-warning"
      style="cursor: pointer"
    >
      <strong class="pl-2 text-neutral-strong">
        {{ $t('not_current_year_reset') }}
      </strong>
    </a>
  </UiSystemBar>
</template>

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

const { em } = useEntityManager()
const accessProfile = useAccessProfileStore()
const organizationProfile = useOrganizationProfileStore()
const { setDirty } = useFormStore()
const pageStore = usePageStore()
const { refreshProfile } = useRefreshProfile()

const show: ComputedRef<boolean> = computed(() => {
  return (
    accessProfile.historical.past ||
    accessProfile.historical.future ||
    (accessProfile.historical.dateStart &&
      accessProfile.historical.dateStart.length > 0) ||
    (accessProfile.historical.dateEnd &&
      accessProfile.historical.dateEnd.length > 0) ||
    accessProfile.activityYear !== organizationProfile.currentActivityYear
  )
})

const resetYear = async () => {
  const defaultValues = {
    historical: {
      future: false,
      past: false,
      present: true,
    },
    activityYear: organizationProfile.currentActivityYear,
  }

  // Il faut ajouter un patch sur le profile ici
  setDirty(false)

  pageStore.loading = true
  await em.patch(Access, accessProfile.currentAccessId, defaultValues)
  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 scoped lang="scss">
.v-system-bar {
  font-size: 14px;
}

.v-icon {
  height: 20px;
  margin: 0 6px;
}

#resetLink:hover {
  cursor: pointer;
}
</style>
