<template>
  <LayoutContainer>
    <UiLoadingPanel v-if="pending" />
    <UiForm
      v-else-if="parameters !== null"
      :model="Parameters"
      :entity="parameters"
      action-position="bottom"
    >
      <v-table>
        <thead>
          <tr>
            <td>{{ $t('originalLabel') }}</td>
            <td>{{ $t('effectiveLabel') }}</td>
          </tr>
        </thead>

        <tbody>
          <tr v-for="enumItem in cycleEnum" :key="enumItem.value">
            <td>{{ $t(enumItem.value) }}</td>
            <td class="cycle-editable-cell">
              {{
                orderedCycles[enumItem.value]
                  ? orderedCycles[enumItem.value].label
                  : $t(enumItem.value)
              }}
            </td>
            <td style="max-width: 24px">
              <v-btn
                v-if="orderedCycles[enumItem.value]"
                :flat="true"
                icon="fa fa-pen"
                class="cycle-edit-icon"
                @click="goToCycleEditPage(orderedCycles[enumItem.value].id)"
              />
            </td>
          </tr>
        </tbody>
      </v-table>

      <UiInputCheckbox
        v-model="parameters.showEducationIsACollectivePractice"
        field="showEducationIsACollectivePractice"
        label="allow_to_configure_teachings_with_played_instrument_choice"
      />
    </UiForm>
  </LayoutContainer>
</template>

<script setup lang="ts">
import type { AsyncData } from '#app'
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 ApiResource from '~/models/ApiResource'

definePageMeta({
  name: 'parameters_teaching_page',
})

const organizationProfile = useOrganizationProfileStore()

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

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

const { data: cycleEnum, pending: enumPending } = fetchEnum('education_cycle')

const { data: parameters, pending: parametersPending } = fetch(
  Parameters,
  organizationProfile.parametersId,
) as AsyncData<ApiResource | null, Error | null>

const { data: cycles, pending: cyclesPending } = fetchCollection(Cycle)

const pending: ComputedRef<boolean> = computed(
  () => enumPending.value || parametersPending.value || cyclesPending.value,
)

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 goToCycleEditPage = (id: number) => {
  navigateTo(`/parameters/cycles/${id}`)
}
</script>

<style scoped lang="scss">
.v-table {
  width: 100%;
  max-width: 800px;
}

.cycle-edit-icon {
  color: rgb(var(--v-theme-primary));
}

:deep(.cycle-edit-icon .v-icon) {
  font-size: 18px;
}
</style>
