<template>
    <div>
        <div v-if="isOpen" class="dialog-overlay">
            <div class="dialog-content">
                <h3>Kontaktperson hinzufügen</h3>
                <div>
                    <label for="type-select">Typen:</label>
                    <multiselect id="type-select" v-model="selectedTypes" :options="typeOptions" :multiple="true"
                        label="caption" track-by="id" @select="onTypeSelect" />
                </div>
                <div v-if="selectedTypes.some(type => type.id === 'places')">
                    <label for="places-select">Wählen Sie Orte:</label>
                    <multiselect id="places-select" v-model="selectedPlaces" :options="places" :multiple="true"
                        label="name" track-by="id" />
                </div>
                <div v-if="selectedTypes.some(type => type.id === 'types')">
                    <label for="types-select">Wählen Sie Typen:</label>
                    <multiselect id="types-select" v-model="selectedEventTypes" :options="eventTypes" :multiple="true"
                        label="caption" track-by="id" />
                </div>
                <div v-if="selectedTypes.some(type => type.id === 'position')">
                    <label for="position-select">Wählen Sie eine Position:</label>
                    <multiselect id="position-select" v-model="selectedPositions" :options="positions" :multiple="false"
                        label="caption" track-by="id" />
                </div>
                <div v-if="selectedTypes.some(type => type.id === 'specific')">
                    <label for="contact-select">Wählen Sie eine Kontaktperson:</label>
                    <multiselect id="contact-select" v-model="selectedContact" :options="contacts" :multiple="false"
                        label="name" track-by="id" />
                </div>
                <div>
                    <label>Wählen Sie welche Elemente angezeigt werden sollen:</label>
                    <div class="display-options">
                        <label><input type="checkbox" v-model="displayOptions.phone" /> Telefon</label>
                        <label><input type="checkbox" v-model="displayOptions.street" /> Straße</label>
                        <label><input type="checkbox" v-model="displayOptions.zipcode" /> Postleitzahl</label>
                        <label><input type="checkbox" v-model="displayOptions.city" /> Stadt</label>
                        <label><input type="checkbox" v-model="displayOptions.email" /> E-Mail</label>
                        <label><input type="checkbox" v-model="displayOptions.positions" /> Positionen</label>
                    </div>
                    <div>
                        <label for="displayStyle">Anzeigen als</label>
                        <select id="displayStyle" v-model="displayStyle">
                            <option v-for="style in displayStyles" :value="style.id" :key="style.id">{{ style.label }}</option>
                        </select>
                    </div>
                </div>
                <div>
                    <button @click="confirmAddContactConfiguration">Bestätigen</button>
                    <button @click="closeAddContactDialog">Schließen</button>
                </div>
            </div>
        </div>
    </div>
</template>

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

export default {
    name: 'AddContactDialog',
    components: {
        Multiselect,
    },
    emits: ['confirm'],
    setup(props, { emit }) {
        const isOpen = ref(false);
        const contacts = ref([]);
        const eventTypes = ref([]);
        const places = ref([]);
        const positions = ref([]);
        const selectedContact = ref(null);
        const selectedTypes = ref([]);
        const selectedEventTypes = ref([]);
        const selectedPositions = ref([]);
        const selectedPlaces = ref([]);
        const displayStyle = ref('float');

        const displayOptions = ref({
            phone: false,
            street: false,
            zipcode: false,
            city: false,
            email: false,
            positions: false,
        });

        const typeOptions = ref([
            { id: 'all', caption: 'Alle' },
            { id: 'specific', caption: 'Eine Person' },
            { id: 'places', caption: 'Für bestimmte Orte' },
            { id: 'types', caption: 'Für bestimmte Typen' },
            { id: 'position', caption: 'Für bestimmte Positionen'}
        ]);

        const displayStyles = ref([
            { id: 'float', label: 'Durchlaufender Text' },
            { id: 'box', label: 'Textbox' },
        ]);

        const openAddContactDialog = () => {
            isOpen.value = true;
            fetchContacts();
            fetchEventTypes();
            fetchPlaces();
            fetchPositions();
        };

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

        const onTypeSelect = () => {
            if (selectedTypes.value.some(type => type.id === 'all')) {
                selectedTypes.value = [{ id: 'all', caption: 'Alle' }];
                selectedContact.value = null;
                selectedEventTypes.value = [];
                selectedPlaces.value = [];
                selectedPositions.value = [];
            } else if (selectedTypes.value.some(type => type.id === 'specific')) {
                selectedTypes.value = [{ id: 'specific', caption: 'Eine Person' }];
                selectedEventTypes.value = [];
                selectedPlaces.value = [];
                selectedPositions.value = [];
            } else if (selectedTypes.value.some(type => type.id === 'places')) {
                selectedContact.value = null;
            } else if (selectedTypes.value.some(type => type.id === 'types')) {
                selectedContact.value = null;
            } else if (selectedTypes.value.some(type => type.id === 'position')) {
                selectedContact.value = null;
            }
        };

        const confirmAddContactConfiguration = () => {
            console.log('Selected positions:', selectedPositions.value); // Log the selected positions
            let configString = '';
            const displayArray = Object.keys(displayOptions.value).filter((key) => displayOptions.value[key]);
            let selection = {};
            if (selectedTypes.value.some(type => type.id === 'all')) {
                selection['id'] = 'all';
            } else if (selectedTypes.value.some(type => type.id === 'specific') && selectedContact.value) {
                selection['id'] = selectedContact.value.id;
            } else {
                selection['types'] = selectedEventTypes.value.map((type) => type.id);
                selection['places'] = selectedPlaces.value.map((place) => place.id);
                selection['positions'] = Array.isArray(selectedPositions.value) ? selectedPositions.value.map((position) => position.id) : [];
            }
            const contact = {
                selection: selection,
                display: displayArray,
                style: displayStyle.value
            }
            configString = '{{ contact:' + JSON.stringify(contact) + ' }}';
            console.log('Emitting config:', configString); // Log the emitted config
            emit('confirm', configString);
            closeAddContactDialog();
        };

        const fetchContacts = async () => {
            try {
                const response = await axios.get('/contact-persons');
                contacts.value = response.data;
            } catch (error) {
                console.error('Fehler beim Laden der Kontaktpersonen:', error);
            }
        };

        const fetchEventTypes = async () => {
            try {
                const response = await axios.get('/event-types');
                eventTypes.value = response.data;
            } catch (error) {
                console.error('Fehler beim Laden der Event-Typen:', error);
            }
        };

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

        const fetchPositions = async () => {
            try {
                const response = await axios.get('/positions');
                positions.value = response.data;
            } catch (error) {
                console.error('Fehler beim Laden der Positionen:', error)
            }
        }

        return {
            isOpen,
            contacts,
            selectedContact,
            selectedTypes,
            selectedEventTypes,
            selectedPlaces,
            displayOptions,
            displayStyle,
            displayStyles,
            typeOptions,
            openAddContactDialog,
            closeAddContactDialog,
            confirmAddContactConfiguration,
            onTypeSelect,
            places,
            eventTypes,
            positions,
            selectedPositions,
        };
    },
};
</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%;
}

.display-options label {
    display: block;
}
</style>
