<script setup lang="ts">
const props = defineProps<{
  bookRecommendationId: number
}>()
const isOpen = ref(false)
const loading = ref(false)

const dayjs = useDayjs()
const form = ref()

interface NewDeadlineState {
  book_recommendation_id: number | null
  deadline: string
  target_page?: number
  target_chapter?: string
}

const state: NewDeadlineState = reactive({
  book_recommendation_id: props.bookRecommendationId,
  deadline: '',
  target_page: undefined,
  target_chapter: undefined,
})

async function onSubmit() {
  loading.value = true

  await $fetch('deadlines', {
    method: 'POST',
    body: state,
    headers: {
      'Content-Type': 'application/json',
    },
    async onResponse({ response }) {
      loading.value = false
      if (response?.status === 422) {
        form.value.setErrors(response._data?.errors)
      }
      else if (response.ok) {
        useToast().add({
          icon: 'i-heroicons-check-circle-20-solid',
          title: 'Deadline erfolgreich erstellt.',
          color: 'emerald',
        })
        loading.value = false

        isOpen.value = false
      }
    },
  })
}
</script>

<template>
  <div>
    <UButton icon="i-heroicons-plus" label="Neue Deadline" size="sm" variant="solid" color="green" square @click="isOpen = true" />
    <UModal v-model="isOpen">
      <UCard :ui="{ ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
        <template #header>
          <div class="flex items-center justify-between">
            <h3 class="text-base font-semibold leading-6 text-gray-900 dark:text-white">
              Neue Deadline
            </h3>
            <UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1" @click="isOpen = false" />
          </div>
        </template>

        <UForm ref="form" :state="state" class="space-y-4" @submit="onSubmit">
          <UFormGroup label="Deadline" name="deadline">
            <UInput v-model="state.deadline" type="date" />
          </UFormGroup>
          <UFormGroup label="Zielseite" name="target_page">
            <UInput v-model="state.target_page" type="number" />
          </UFormGroup>
          <UFormGroup label="Zielkapitel" name="target_chapter">
            <UInput v-model="state.target_chapter" />
          </UFormGroup>
          <UButton size="md" type="submit" :loading="loading">
            Erstellen
          </UButton>
          <UButton size="md" class="mx-4" color="white" label="Abbrechen" @click="isOpen = false" />
        </UForm>
      </UCard>
    </UModal>
  </div>
</template>
