<template>
    <div class="flex flex-col gap-5 mx-auto p-2 w-full max-w-md">
        <form @submit.prevent="sendNews" class="flex flex-col">
            <label class="font-bold">Title</label>
            <input v-model="form.title" required="true" class="input mb-5" type="text">

            <label class="font-bold">Description</label>
            <textarea v-model="form.description" required="true" class="input mb-5" />

            <div class="w-full flex flex-wrap justify-between">
                <input :disabled="disableButtons" type="submit" value="Stuur Bericht" class="btn w-full sm:w-40 mb-1">
                <button @click="router.back()" class="hover:underline font-bold w-full sm:w-max sm:ml-auto">Cancel</button>
            </div>
        </form>
    </div>
</template>

<script setup>
import { addDoc, collection, serverTimestamp, Timestamp } from 'firebase/firestore'
import { useToast } from 'vue-toastification'

definePageMeta({
    title: 'Nieuw Bericht',
    key: 'back'
})

const { news, userData, db, auth } = inject('firebase')
const router = useRouter()
const toast = useToast()

const disableButtons = ref(false)

const form = ref({
    title: '',
    description: '',
})

const sendNews = async () => {
    disableButtons.value = true

    try {
        const idToken = await auth.value.currentUser.getIdToken(true)
        console.log(idToken)

        await fetch('https://api.xeovalyte.com/sendmessage', {
            method: 'POST',
            headers: {
            Authorization: 'Basic WGVvdmFseXRlOmtNKjhuRXMzNTchalJlXm1KYnZrRSFOIw==',
            'content-type': 'application/json'
            },
            body: JSON.stringify({ title: form.value.title, body: form.value.description, token: idToken })
        }).then(response => response.json())
            .then(async response => {
                console.log(response)

                await addDoc(collection(db, "news"), {
                    title: form.value.title,
                    description: form.value.description,
                    date: serverTimestamp()
                });

                if (news.value) {
                    news.value.unshift({
                        title: form.value.title,
                        description: form.value.description,
                        date: Timestamp.now()
                    })
                }
                toast.success('Bericht is verstuurd')

                navigateTo('/news')
            })
            .catch(err => {
                console.log(err)

                toast.error('Error tijdens het berict sturen')
            });
    } catch (e) {
        console.log(e)

        toast.error('Error tijdens het berict sturen')
        
    }
    

    disableButtons.value = false
}
</script>