<template>
  <main class="d-flex align-baseline">
    <span v-show="mdAndUp" class="mr-2 font-weight-bold">{{ $t('display_data') }} : </span>

    <v-btn-toggle
      ref="toggle"
      :model-value="historicalValue"
      density="compact"
      :color="color"
      multiple
      divider
      border
      :rounded="true"
      class="toggle-btn"
      @update:modelValue="onUpdate"
    >
      <v-btn
          v-for="choice in historicalChoices"
          :value="choice"
          max-height="25"
          :class="'font-weight-normal text-caption ' + (historicalValue.includes(choice) ? 'theme-primary' : 'theme-neutral-soft')"
      >
        <!-- TODO: on ne devrait pas avoir besoin du if et de la classe 'btn-selected' dans v-btn, mais à l'heure
         qu'il est, le component ne fonctionne pas comme attendu. A revoir quand vuetify 3 sera plus stable -->
        {{ $t(choice) }}
      </v-btn>
    </v-btn-toggle>
  </main>
</template>

<script setup lang="ts">
import {useFormStore} from "~/stores/form";
import {useAccessProfileStore} from "~/stores/accessProfile";
import {Ref} from "@vue/reactivity";
import {useEntityManager} from "~/composables/data/useEntityManager";
import {useDisplay, useTheme} from "vuetify";
import Access from "~/models/Access/Access";

// TODO: en v3.0.5, pas de solution documentée pour renseigner directement la couleur dans le template, à revoir
const color = useTheme().current.value.colors['primary']

const { setDirty } = useFormStore()
const accessProfileStore = useAccessProfileStore()
const { em } = useEntityManager()
const { mdAndUp } = useDisplay()

const toggle = ref(null)

const historicalChoices: Array<'past' | 'present' | 'future'> = ['past', 'present', 'future']

const historicalValue: Ref<Array<string>> = ref(historicalChoices.filter((item) => accessProfileStore.historical[item]))

const onUpdate = async (newValue: Array<string>) => {
  historicalValue.value = newValue

  if (accessProfileStore.id === null) {
    throw new Error('Invalid profile id')
  }

  accessProfileStore.setHistorical(
      historicalValue.value.includes('past'),
      historicalValue.value.includes('present'),
      historicalValue.value.includes('future')
  )

  setDirty(false)

  await em.patch(
      Access,
      accessProfileStore.id,
      {'historical': accessProfileStore.historical}
  )

  window.location.reload()
}

</script>

<style scoped lang="scss">
  .v-btn-group {
    max-height: 22px;
  }

  .v-btn {
    padding: 0 8px;
  }

  .v-btn.btn-selected {
    background-color: rgb(var(--v-theme-primary)) !important;
  }
</style>
