<template>
    <div class="forums-admin">
        <h2>{{ $t('admin.forum.title') }}</h2>

        <div class="forum-list">
            <h3>{{ $t('admin.forum.currentForums') }}</h3>
            <ul>
                <li v-for="forum in forums" :key="forum.id" class="forum-item">
                    <div class="forum-info">
                        <strong>{{ forum.name }}</strong>
                        <button @click="editForum(forum)" class="btn btn-sm">{{ $t('admin.forum.edit') }}</button>
                        <button @click="confirmDelete(forum)" class="btn btn-sm btn-danger">{{ $t('admin.forum.delete')
                            }}</button>
                    </div>
                </li>
            </ul>
        </div>

        <div class="create-forum">
            <h3 v-if="!inEdit">{{ $t('admin.forum.createForum') }}</h3>
            <h3 v-else>{{ $t('admin.forum.editForum') }}</h3>
            <button v-if="inEdit" @click="toggleToNewForum">{{  $t('admin.forum.toggleToNewForum') }}</button>
            <form @submit.prevent="submitNewForum">
                <div>
                    <label for="name">{{ $t('admin.forum.forumName') }}</label>
                    <input v-model="newForum.name" id="name" type="text" required />
                </div>
                <div>
                    <label for="permissions">{{ $t('admin.forum.permissions.label') }}</label>
                    <multiselect v-model="newForum.permissions" :options="permissionsOptions" :multiple="true"
                        :close-on-select="false" :clear-on-select="false" :preserve-search="true"
                        :placeholder="$t('admin.forum.selectPermissions')" label="label" track-by="value">
                        <template v-slot:option="option">
                            {{ $t(`admin.${option.option.label}`) }}
                        </template>
                        <template v-slot:tag="tag">
                            <span>{{ $t(`admin.${tag.option.label}`) }}</span>
                        </template>
                    </multiselect>
                </div>
                <button type="submit" class="btn btn-primary">{{ $t('admin.forum.create') }}</button>
            </form>
        </div>
        <choose-dialog ref="confirmDialog" />
    </div>
</template>

<script>
import apiClient from '@/utils/axios.js';
import ChooseDialog from '@/dialogues/standard/ChooseDialog.vue';
import Multiselect from 'vue-multiselect';

export default {
    name: 'ForumsAdminView',
    components: {
        ChooseDialog,
        Multiselect,
    },
    data() {
        return {
            forums: [],
            newForum: {
                name: '',
                permissions: [],
            },
            permissionsOptions: [
                { value: 'all', label: this.$t('forum.permissions.all') },
                { value: 'admin', label: this.$t('forum.permissions.admin') },
                { value: 'teammember', label: this.$t('forum.permissions.teammember') },
                { value: 'user', label: this.$t('forum.permissions.user') },
                { value: 'age', label: this.$t('forum.permissions.age') },
            ],
            inEdit: false,
        };
    },
    methods: {
        async loadForums() {
            try {
                const response = await apiClient.get('/api/forum');
                this.forums = response.data;
            } catch (error) {
                console.error('Error loading forums:', error);
            }
        },
        async submitNewForum() {
            try {
                await apiClient.post('/api/forum', {
                    name: this.newForum.name,
                    permissions: this.newForum.permissions.map(p => p.value),
                });
                this.newForum.name = '';
                this.newForum.permissions = [];
                this.loadForums(); 
            } catch (error) {
                console.error('Error creating forum:', error);
            }
        },
        editForum(forum) {
            this.inEdit = true;
            this.newForum.name = forum.name;
            this.newForum.permissions = forum.permissions;
        },
        toggleToNewForum() {
            this.inEdit = false;
            this.newForum.name = '';
            this.newForum.permissions = '';
        },
        async deleteForum(forum) {
            try {
                await apiClient.delete(`/api/forum/${forum.id}`);
                this.loadForums();
            } catch (error) {
                console.error('Error deleting forum:', error);
            }
        },
        async confirmDelete(forum) {
            const confirmed = await this.$refs.confirmDialog.open({
                title: this.$t('admin.forum.confirmDeleteTitle'),
                message: this.$t('admin.forum.confirmDeleteMessage', { forumName: forum.name }),
            });
            if (confirmed) {
                this.deleteForum(forum);
            }
        },
    },
    mounted() {
        this.loadForums();
    },
};
</script>

<style scoped>
.forums-admin {
    max-width: 800px;
    margin: 0 auto;
}

.forum-list ul {
    list-style: none;
    padding: 0;
}

.forum-item {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #ccc;
}

.forum-info {
    display: flex;
    justify-content: space-between;
    width: 100%;
}

.forum-info > strong {
    flex: 1;
}

.create-forum form {
    margin-top: 20px;
}

.create-forum form div {
    margin-bottom: 10px;
}
</style>
