<script setup>
import {NModal, NList, NListItem, NThing, NAvatar, NIcon, NDrawer, NDrawerContent,
    NText, NDivider, NForm, NFormItem, NInput, NFlex, NButton, NScrollbar, NEmpty
} from 'naive-ui'
import {useReportStore} from "../../../Stores/report.js";
import {ref} from "vue";
const open = defineModel('open')
import { TbAlertCircle, TbPencil, TbTrashX, TbCirclePlus, TbCheck, TbX } from 'vue-icons-plus/tb'
import {format, isValid} from "date-fns";

const reportStore = useReportStore()
const formRef = ref()
const createDrawerShow = ref(false)
const rules = {
    comment: {
        required: true,
        message: 'Заполните этот блок',
        trigger: 'blur'
    }
}
const selectedEvent = ref(null)
const drawerCreatingMode = ref(true) // or false = editing

// Создание в сторе и открытие drawer с формой нежелательного события
const onCreateEvent = () => {
    drawerCreatingMode.value = true
    const createDate = format(new Date(), 'Создано dd.MM.yyyy в HH:mm')
    reportStore.unwantedEvents.push({
        title: `Нежелательное событие №${reportStore.unwantedEvents.length + 1}`,
        comment: '',
        created_at: createDate
    })

    const length = reportStore.unwantedEvents.length

    selectedEvent.value = reportStore.unwantedEvents[length - 1]
    createDrawerShow.value = true
}

const onEditEvent = (event) => {
    drawerCreatingMode.value = false
    selectedEvent.value = event
    createDrawerShow.value = true
}

const onDeleteEvent = (event) => {
    const indexOfDelete = reportStore.unwantedEvents.findIndex(itm => itm === event)

    if (typeof event.unwanted_event_id !== 'undefined') {
        axios.delete(`/api/report/unwanted-event/${event.unwanted_event_id}`)
            .then(() => {
                reportStore.unwantedEvents.splice(indexOfDelete, 1)
            })
    } else {
        reportStore.unwantedEvents.splice(indexOfDelete, 1)
    }
}

const onCancelDrawerEvent = (event) => {
    onDeleteEvent(event)
    createDrawerShow.value = false
}

const onCreateDrawerEvent = () => {
    formRef.value?.validate((errors) => {
        if (!errors) {
            console.log(createDrawerShow.value)
            createDrawerShow.value = false
            console.log(createDrawerShow.value)
        }
        else {

        }
    })
}

const onBeforeLeaveModal = () => {
    selectedEvent.value = null
    drawerCreatingMode.value = true
    createDrawerShow.value = false
}
</script>

<template>
    <NModal v-model:show="open"
            title="Нежелательные события"
            preset="card"
            :mask-closable="false"
            :close-on-esc="false"
            @before-leave="onBeforeLeaveModal"
            class="max-w-4xl overflow-clip h-[calc(100vh-220px)]"
    >
        <template v-if="reportStore.unwantedEvents.length">
            <NScrollbar class="max-h-[calc(100vh-282px)] pr-3">
                <NList>
                    <NListItem v-for="event in reportStore.unwantedEvents">
                        <NThing>
                            <template #avatar>
                                <NAvatar>
                                    <NIcon>
                                        <TbAlertCircle class="text-red-400" />
                                    </NIcon>
                                </NAvatar>
                            </template>
                            <template #header>
                                {{ event.title }}
                            </template>
                            <template #description>
                                <NText depth="3">
                                    {{ event.created_at }}
                                </NText>
                            </template>
                            <NText>
                                {{ event.comment }}
                            </NText>
                            <template #action>
                                <NFlex align="center">
                                    <NButton secondary size="small" @click="onEditEvent(event)">
                                        <template #icon>
                                            <TbPencil />
                                        </template>
                                        Редактировать
                                    </NButton>
                                    <NDivider vertical />
                                    <NButton type="error" secondary size="small" @click="onDeleteEvent(event)">
                                        <template #icon>
                                            <TbTrashX />
                                        </template>
                                        Удалить
                                    </NButton>
                                </NFlex>
                            </template>
                        </NThing>
                    </NListItem>
                </NList>
            </NScrollbar>
        </template>
        <template v-else>
            <div class="h-full flex items-center justify-center">
                <NEmpty description="Нежелательных событий не найдено!">
                    <template #extra>
                        <NButton type="primary" secondary @click="onCreateEvent()" size="small">
                            <template #icon>
                                <TbCirclePlus />
                            </template>
                            Создать
                        </NButton>
                    </template>
                </NEmpty>
            </div>
        </template>

        <template #action>
            <NFlex id="modal-action" align="center" justify="space-between">
                <NButton type="primary" secondary @click="onCreateEvent()">
                    <template #icon>
                        <TbCirclePlus />
                    </template>
                    Создать событие
                </NButton>
            </NFlex>
        </template>

        <NDrawer
            :show="createDrawerShow"
            placement="bottom"
            :max-height="600"
            :min-height="400"
            :default-height="400"
            resizable
            :trap-focus="false"
            :block-scroll="false"
            :mask-closable="false"
            to="#modal-action"
        >
            <NDrawerContent>
                <template #header>
                    <template v-if="drawerCreatingMode">Создание события</template>
                    <template v-else>Редактирование события</template>
                </template>
                <NForm ref="formRef" :model="selectedEvent" :rules="rules">
                    <NFormItem :show-label="false" path="comment">
                        <NInput type="textarea" :rows="8" v-model:value="selectedEvent.comment" />
                    </NFormItem>
                </NForm>
                <template #footer>
                    <NFlex align="center">
                        <NButton v-if="drawerCreatingMode" type="error" secondary @click="onCancelDrawerEvent(selectedEvent)">
                            <template #icon>
                                <TbX />
                            </template>
                            Отменить создание
                        </NButton>
                        <NDivider v-if="drawerCreatingMode" vertical />
                        <NButton type="primary" @click="onCreateDrawerEvent">
                            <template #icon>
                                <TbCheck />
                            </template>
                            <template v-if="drawerCreatingMode">Создать</template>
                            <template v-else>Сохранить</template>
                        </NButton>
                    </NFlex>
                </template>
            </NDrawerContent>
        </NDrawer>
    </NModal>
</template>

<style scoped>

</style>
