<template>
    <h2>{{ $t('socialnetwork.diary.title') }}</h2>

    <div class="new-entry-section">
        <h3>{{ isEditing ? $t('socialnetwork.diary.editEntry') : $t('socialnetwork.diary.newEntry') }}</h3>
        <textarea v-model="newEntryText" placeholder="Write your diary entry..."></textarea>
        <div class="form-actions">
            <button @click="saveEntry">{{ isEditing ? $t('socialnetwork.diary.update') : $t('socialnetwork.diary.save')
                }}</button>
            <button v-if="isEditing" @click="cancelEdit">{{ $t('socialnetwork.diary.cancel') }}</button>
        </div>
    </div>

    <div v-if="diaryEntries.length === 0">{{ $t('socialnetwork.diary.noEntries') }}</div>
    <div v-else class="diary-entries">
        <div v-for="entry in diaryEntries" :key="entry.id" class="diary-entry">
            <p v-html="sanitizedText(entry)"></p>
            <div class="entry-info">
                <span class="entry-timestamp">{{ new Date(entry.createdAt).toLocaleString() }}</span>
                <span class="entry-actions">
                    <span @click="editEntry(entry)" class="button" :title="$t('socialnetwork.diary.edit')">✎</span>
                    <span @click="deleteEntry(entry.id)" class="button" :title="$t('socialnetwork.diary.delete')">✖</span>
                </span>
            </div>
        </div>
    </div>

    <div class=" pagination">
        <button @click="loadDiaryEntries(currentPage - 1)" v-if="currentPage !== 1">{{
            $t('socialnetwork.diary.prevPage') }}</button>
        <span>{{ $t('socialnetwork.diary.page') }} {{ currentPage }} / {{ totalPages }}</span>
        <button @click="loadDiaryEntries(currentPage + 1)" v-if="currentPage < totalPages">{{
            $t('socialnetwork.diary.nextPage') }}</button>
    </div>
    <ChooseDialog ref="chooseDialog" />
</template>

<script>
import { mapGetters } from 'vuex';
import apiClient from '@/utils/axios.js';
import ChooseDialog from "@/dialogues/standard/ChooseDialog.vue";
import DOMPurify from 'dompurify';

export default {
    name: 'DiaryView',
    components: {
        ChooseDialog
    },
    data() {
        return {
            diaryEntries: [],
            newEntryText: '', 
            currentPage: 1,
            totalPages: 1,
            isEditing: false, 
            editingEntryId: null,
        };
    },
    computed: {
        ...mapGetters(['user']),
    },
    methods: {
        sanitizedText(entry) {
            return DOMPurify.sanitize(entry.text);
        },
        async loadDiaryEntries(page) {
            try {
                console.log(page);
                const response = await apiClient.get(`/api/socialnetwork/diary/${page}`);
                this.diaryEntries = response.data.entries;
                this.currentPage = page;
                this.totalPages = response.data.totalPages;
            } catch (error) {
                console.error('Error loading diary entries:', error);
            }
        },

        async saveEntry() {
            if (!this.newEntryText) return;

            try {
                if (this.isEditing) {
                    await apiClient.put(`/api/socialnetwork/diary/${this.editingEntryId}`, {
                        text: this.newEntryText,
                    });
                    this.isEditing = false;
                    this.editingEntryId = null;
                } else {
                    await apiClient.post(`/api/socialnetwork/diary`, {
                        text: this.newEntryText,
                        userId: this.user.id,
                    });
                }
                this.newEntryText = '';
                this.loadDiaryEntries(this.currentPage);
            } catch (error) {
                console.error('Error saving entry:', error);
            }
        },

        editEntry(entry) {
            this.isEditing = true;
            this.newEntryText = entry.text;
            this.editingEntryId = entry.id;
        },

        cancelEdit() {
            this.isEditing = false;
            this.newEntryText = '';
            this.editingEntryId = null;
        },

        async confirmDeleteEntry(entryId) {
            const confirmed = await this.$refs.chooseDialog.open({
                title: this.$t('socialnetwork.diary.confirmDeleteTitle'),
                message: this.$t('socialnetwork.diary.confirmDeleteMessage')
            });

            if (confirmed) {
                this.deleteEntry(entryId);
            }
        },

        async deleteEntry(entryId) {
            try {
                await apiClient.delete(`/api/socialnetwork/diary/${entryId}`);
                this.loadDiaryEntries(this.currentPage);
            } catch (error) {
                console.error('Error deleting entry:', error);
            }
        }
    },
    mounted() {
        this.loadDiaryEntries(1);
    },
};
</script>

<style scoped>
.new-entry-section {
    margin-bottom: 20px;
}

textarea {
    width: 100%;
    height: 100px;
    margin-bottom: 10px;
}

.form-actions button {
    margin-right: 10px;
}

.diary-entry {
    border-bottom: 1px solid #ccc;
    margin-bottom: 1em;
    padding-bottom: 1em;
}

.entry-info {
    color: gray;
    display: flex;
    flex-direction: row;
}

.entry-timestamp {
        font-size: 0.8em;
}
.entry-actions {
    flex: 1;
    text-align: right;
}
.entry-actions button {
    margin-right: 10px;
}

.pagination {
    margin-top: 1em;
    background-color: #7BBE55;
    color: #fff;
    padding: 0.5em 0;
}

.diary-entries {
    width: 400px;
}

</style>
