<template>
    <div>
        <div v-if="isOpen" class="dialog-overlay">
            <div class="dialog-content">
                <h3>Gottesdienst-Konfiguration</h3>
                <div>
                    <label for="location-select">Bitte wählen Sie den Ort für den Gottestdienst aus:</label>
                </div>
                <div>
                    <multiselect
                        v-model="selectedLocations"
                        :options="locations"
                        :multiple="true"
                        :close-on-select="false"
                        :clear-on-select="false"
                        :preserve-search="true"
                        :preselect-first="false"
                        label="name"
                        track-by="id"
                        placeholder="Orte auswählen"
                    >
                    </multiselect>
                </div>
                <div>
                    <button @click="confirmWorshipConfiguration">Bestätigen</button>
                    <button @click="closeWorshipDialog">Schließen</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { ref } from 'vue';
import axios from '@/axios';
import Multiselect from 'vue-multiselect';
import 'vue-multiselect/dist/vue-multiselect.css';

export default {
    name: 'WorshipDialog',
    components: {
        Multiselect
    },
    emits: ['confirm'],
    setup(props, { emit }) {
        const isOpen = ref(false);
        const locations = ref([]);
        const selectedLocations = ref([]);

        const openWorshipDialog = () => {
            isOpen.value = true;
            fetchLocations();
        };

        const closeWorshipDialog = () => {
            isOpen.value = false;
        };

        const fetchLocations = async () => {
            try {
                const response = await axios.get('/event-places');
                locations.value = response.data;
            } catch (error) {
                console.error('Fehler beim Laden der Orte:', error);
            }
        };

        const confirmWorshipConfiguration = () => {
            const selectedLocationIds = JSON.stringify(selectedLocations.value.map(location => location.id));
            emit('confirm', selectedLocationIds);
            closeWorshipDialog();
        };

        return {
            isOpen,
            locations,
            selectedLocations,
            openWorshipDialog,
            closeWorshipDialog,
            confirmWorshipConfiguration,
        };
    },
};
</script>

<style scoped>
.dialog-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
}

.dialog-content {
    background: white;
    padding: 20px;
    border-radius: 8px;
}

.multiselect {
    width: 100%;
}
</style>
