<script setup lang="ts">
import { useBookRecommendationStore } from '~/stores/book-recommendations'

const props = defineProps<{
  row: {
    id: number
    book_name: string
  }
}>()

const isOpen = ref(false)

const authStore = useAuthStore()

const state = reactive({
  book_recommendation_id: props.row.id,
})

const bookRecommendationStore = useBookRecommendationStore()

const { refresh: onVote, status } = useFetch<any>(`vote`, {
  method: 'POST',
  body: state,
  immediate: false,
  watch: false,
  async onResponse({ response }) {
    if (response.ok) {
      useToast().add({
        icon: 'i-heroicons-check-circle-20-solid',
        title: 'Abstimmung erfolgreich.',
        color: 'emerald',
      })
      await bookRecommendationStore.fetchRecommendations()
      await authStore.fetchUser()
      isOpen.value = false
    }
  },
})
</script>

<template>
  <UButton icon="i-heroicons-star" size="sm" color="green" variant="solid" square :disabled="authStore.user.total_votes === 0" @click="isOpen = true" />
  <UDashboardModal
    v-model="isOpen"
    title="Buch Empfehlung löschen"
    :description="`Bist du dir sicher das du für die Buchempfehlung ${row.book_name} abstimmen möchtest?`"
    icon="i-heroicons-star"
    :ui="{
      icon: { base: 'text-green-500 dark:text-green-400' } as any,
      footer: { base: 'ml-16' } as any,
    }"
  >
    <template #footer>
      <UButton color="primary" label="Abstimmung" :loading="status === 'pending'" @click="onVote" />
      <UButton color="white" label="Abbrechen" @click="isOpen = false" />
    </template>
  </UDashboardModal>
</template>
