<template>
    <div class="mx-2 p-2">
        <div v-if="modal" class="modal-container" @click="modal = ! modal"></div>
        <div v-if="modal" class="modal">
            <p class="m-2 text-center">Are you sure you want to delete this record ?</p>
            <div class="flex justify-center mx-2 my-4">
                <button class="btn mr-2" @click="modal = ! modal">Cancel</button>
                <button class="btn-alert" @click="destroy"> Delete</button>
            </div>
        </div>
        <div class="flex justify-between items-center flex-wrap flex-center mb-4">
            <a href="#" class="btn" @click="$router.back()">Back</a>
            <div>
                <router-link :to="'/events/' + $route.params.id + '/edit'" class="btn-primary">Update Event</router-link>
                <a href="#" class="btn-alert" @click="modal = ! modal">Delete</a>
            </div>
        </div>
        <Loader v-if="loading" />
        <div v-else class="box">
            <div class="flex justify-between flex-wrap">
                <h1 class="text-xl text-marine">{{ event.data.attributes.data.name }}</h1>
                <h2 class="text-sm text-marine">{{ event.data.attributes.data.location }}</h2>
            </div>

            <div v-if="event.data.attributes.data.description">{{ event.data.attributes.data.description }}</div>
            <div class="flex justify-between">
                <span class="mt-auto self-end bg-gray-400 text-white tag">{{ event.data.attributes.data.category.data.attributes.data.name }}</span>
                <span class="mt-auto self-end bg-gray-400 text-white tag">{{ event.data.attributes.data.start_date }}</span>
            </div>
        </div>
    </div>
</template>

<script>
import Loader from '../../components/Loader'

export default {
    name: 'EventShow',
    components: {
        Loader
    },
    data: function () {
        return {
            loading: true,
            modal: false,
            event: null,
        }
    },
    mounted() {
        // eslint-disable-next-line no-undef
        axios.get('/api/events/' + this.$route.params.id)
            .then(response => {
                this.event = response.data
                this.loading = false
            })
            .catch(() => {
                this.loading = false
                console.log('Unable to fetch events.')
            })
    },
    methods: {
        destroy: function () {
            // eslint-disable-next-line no-undef
            axios.delete('/api/events/' + this.$route.params.id)
                .then(() => {
                    this.$router.push('/events')
                })
                .catch(errorRes => {
                    console.log('Internal Error, Unable to delete event.' + errorRes)
                })
        }
    }
}
</script>

