<template>
  <LayoutContainer>
    <LayoutCommonSection>
      <h4>{{ $t('configuration') }}</h4>

      <UiFormEdition :model="Parameters" :id="organizationProfile.parametersId">
        <template #default="{ entity : parameters }">
          <div v-if="parameters">
            <v-row>
              <v-col cols="12">
                <UiInputCheckbox
                  v-model="parameters.showEducationIsACollectivePractice"
                  field="showEducationIsACollectivePractice"
                  label="allow_to_configure_teachings_with_played_instrument_choice"
                />
              </v-col>
            </v-row>
          </div>
        </template>
      </UiFormEdition>
    </LayoutCommonSection>

    <LayoutCommonSection>
      <LayoutParametersTable
        :items="tableItems"
        :title="$t('teaching_cycles')"
        :columns-definitions="[
          { property: 'originalLabel' },
          { property: 'effectiveLabel' },
        ]"
        identifier="value"
        :actions="[TABLE_ACTION.EDIT]"
        @edit-clicked="goToCycleEditPage"
      />
    </LayoutCommonSection>
  </LayoutContainer>
</template>

<script setup lang="ts">
import type { ComputedRef } from 'vue'
import Parameters from '~/models/Organization/Parameters'
import { useEntityFetch } from '~/composables/data/useEntityFetch'
import Cycle from '~/models/Education/Cycle'
import { useOrganizationProfileStore } from '~/stores/organizationProfile'
import type { AnyJson } from '~/types/data'
import { useEnumFetch } from '~/composables/data/useEnumFetch'
import { TABLE_ACTION } from '~/types/enum/enums'
import {FETCHING_STATUS} from "~/types/enum/data";

definePageMeta({
  name: 'parameters_teaching_page',
})

const organizationProfile = useOrganizationProfileStore()

if (organizationProfile.parametersId === null) {
  throw new Error('Missing organization parameters id')
}

const { fetchCollection } = useEntityFetch()
const { fetch: fetchEnum } = useEnumFetch()

const { data: cycleEnum, status: enumStatus } = fetchEnum('education_cycle')

const { data: cycles, status: cyclesStatus } = fetchCollection(Cycle)

const pending: ComputedRef<boolean> = computed(
  () => enumStatus.value == FETCHING_STATUS.PENDING || cyclesStatus.value == FETCHING_STATUS.PENDING,
)

const orderedCycles: ComputedRef<AnyJson> = computed(() => {
  if (pending.value || cycleEnum.value === null || cycles.value === null) {
    return []
  }

  const orderedCycles: AnyJson = {}

  for (const enumItem of cycleEnum.value) {
    orderedCycles[enumItem.value] = null
  }

  for (const cycle of cycles.value.items) {
    if (!Object.prototype.hasOwnProperty.call(orderedCycles, cycle.cycleEnum)) {
      console.error('Unknown cycle enum : ' + cycle.cycleEnum)
      continue
    }

    orderedCycles[cycle.cycleEnum] = cycle
  }

  return orderedCycles
})

const tableItems = computed(() => {
  return (
    cycleEnum.value?.map((item) => {
      return {
        value: item.value,
        originalLabel: item.label,
        effectiveLabel: (orderedCycles.value[item.value] ?? item).label,
      }
    }) || []
  )
})

const goToCycleEditPage = (item: object) => {
  const cycle = orderedCycles.value[item.value]
  navigateTo(`/parameters/cycles/${cycle.id}`)
}

// Nettoyer les données lors du démontage du composant
onBeforeUnmount(() => {
  // Nettoyer les références du store si nécessaire
  if (process.client) {
    clearNuxtData('/^' + Cycle.entity + '_many_/')
    useRepo(Cycle).flush()
  }
})
</script>

<style scoped lang="scss"></style>
