<template>
  <router-view
    v-if="timeslot && note"
    :show="show"
    :timeslot="timeslot"
    :note="note"
    :playlist="playlist"
  />
  <FormGroup v-if="loadingErrorList.length > 0" :errors="loadingErrorList">
    <button type="button" class="btn btn-default tw-w-fit" @click="router.back()">
      <icon-system-uicons-arrow-left />
      {{ t('goBack') }}
    </button>
  </FormGroup>
</template>

<script setup lang="ts">
import { ref, watchEffect } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useErrorList, useObjectFromStore } from '@rokoli/bnb/drf'

import { useI18n } from '@/i18n'
import { useNoteStore, usePlaylistStore, useTimeSlotStore } from '@/stores'
import { defineNavigationContext } from '@/stores/nav'
import { newNote } from '@/stores/notes'
import { Show } from '@/types'
import { ensureError } from '@/util'

import FormGroup from '@/components/generic/FormGroup.vue'

const props = defineProps<{
  show: Show
}>()

const router = useRouter()
const route = useRoute()
const { t } = useI18n()
const timeslotStore = useTimeSlotStore()
const noteStore = useNoteStore()
const playlistStore = usePlaylistStore()
const { obj: timeslot } = useObjectFromStore(
  () => parseInt(route.params.episodeId as string),
  timeslotStore,
)
const { obj: note } = useObjectFromStore(() => timeslot.value?.noteId ?? null, noteStore)
const { obj: playlist } = useObjectFromStore(
  () => timeslot.value?.playlistId ?? null,
  playlistStore,
)
const loadingError = ref<Error | undefined>()
const loadingErrorList = useErrorList(loadingError)

defineNavigationContext(() => ({ episode: timeslot }))

// TODO: remove once steering auto-creates notes for timeslots
watchEffect(async () => {
  const ts = timeslot.value
  if (ts && ts.noteId === null) {
    const note = newNote(ts.id, props.show)
    note.title = 'A title...'
    note.content = 'Some content...'
    try {
      const savedNote = await noteStore.create(note)
      await timeslotStore.partialUpdate(ts.id, { noteId: savedNote.id })
    } catch (e) {
      loadingError.value = ensureError(e)
    }
  }
})

watchEffect(() => {
  const showId = timeslot.value?.showId
  // if timeslot.showId doesn’t match the provided show.id,
  // the user might have switched shows with the show selector.
  if (showId && showId !== props.show.id) {
    void router.push({ name: 'show', params: { showId: props.show.id.toString() } })
  }
})
</script>