<script setup lang="ts">
import type { Channel, BackendError } from '~/types'

import axios from 'axios'

import { watch, ref, emit } from 'vue'
import { useI18n } from 'vue-i18n'
import { useModal } from '~/ui/composables/useModal.ts'

import Layout from '~/components/ui/Layout.vue'
import Modal from '~/components/ui/Modal.vue'
import Button from '~/components/ui/Button.vue'
import Input from '~/components/ui/Input.vue'

const { t } = useI18n()

const channel = defineModel<Channel>({required: true})
defineEmits(['created'])
const newAlbumTitle = ref<string>('')

const isLoading = ref(false)
const submittable = ref(false)
const errors = ref<string[]>([])

const {isOpen:show} = useModal('album')

defineEmits(['created'])

watch(show, () => {
  isLoading.value = false
  submittable.value = false
})

// Create a new Album and tell the parent to re-fetch all albums

defineExpose({
  show
})

const submit = async () => {
  isLoading.value = true
  errors.value = []

  try {
    await axios.post('albums/', {
      title: newAlbumTitle.value,
      artist_credit: [channel.value.artist?.id]
    })
  } catch (error) {
    errors.value = (error as BackendError).backendErrors
  }

  emit('created')

  isLoading.value = false
}

</script>

<template>
  <Modal :title="t(channel?.artist?.content_category === 'podcast' ? 'components.channels.AlbumModal.header.newSeries' : 'components.channels.AlbumModal.header.newAlbum')"
    v-model="show"
    class="small"
    :cancel="t('components.channels.AlbumModal.button.cancel')"
  >
    <template #alert>
      <Alert
        v-if="errors.length > 0"
        red
      >
        <h4 class="header">
          {{ t('components.channels.AlbumForm.header.error') }}
        </h4>
        <ul class="list">
          <li
            v-for="(error, key) in errors"
            :key="key"
          >
            {{ error }}
          </li>
        </ul>
      </Alert>
    </template>

    <Layout form
      :class="['ui', {loading: isLoading}, 'form']"
      @submit.stop.prevent
    >
      <Input
        v-model="newAlbumTitle"
        required
        type="text"
        :label="t('components.channels.AlbumForm.label.albumTitle')"
      />
    </Layout>

    <template #actions>
      <Button
        :is-loading="isLoading"
        :disabled="!submittable"
        primary
        @click.stop.prevent="submit()"
      >
        {{ t('components.channels.AlbumModal.button.create') }}
      </Button>
    </template>
  </Modal>
</template>
