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

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

const isOpen = ref(false)

const authStore = useAuthStore()

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

watch(() => props.row, (newRow) => {
  state.book_recommendation_id = newRow.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',
        title: 'Abstimmung erfolgreich.',
        color: 'emerald',
      })
      await bookRecommendationStore.fetchRecommendations()
      await authStore.fetchUser()
      isOpen.value = false
    }
  },
})
</script>

<template>
  <UButton v-if="props.row.status === 'PENDING'" class="transition-150 transform-gpu hover:scale-110" icon="i-heroicons-check-circle" size="sm" color="green" variant="solid" square :disabled="authStore.user.total_votes === 0" @click="isOpen = true" />
  <UDashboardModal
    v-model="isOpen"
    title="Für Buch abstimmen"
    :description="`Bist du dir sicher das du für die Buchempfehlung &quot;${row.book_name}&quot; abstimmen möchtest?`"
    icon="i-heroicons-check-circle"
    :ui="{
      icon: { base: 'text-primary-500 dark:text-primary-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>
