<script setup>
import {onMounted, reactive, ref} from "vue";
import {useAjax} from "../../../../../resources/js/components/ajaxHandler.js";
import TextEditor from "../../../../Views/Components/TextEditor.vue";
import ErrorText from "../../../../Views/Components/ErrorText.vue";
import {toast} from "vue3-toastify";
const { request } = useAjax();


    const props = defineProps({
        event: Object,
        mailToType: String,
        recipientIdentifier: String,
    })

    const data = reactive({
        recipients: null,
    });

onMounted(async () => {
    const groupTypes = ['all', 'signed-off', 'by-local-group', 'by-participation-group'];

    if (!groupTypes.includes(props.mailToType)) {
        console.error('Unknown recipient identifier:', props.recipientIdentifier);
        return;
    }

    const response = await request('/api/v1/event/' + props.event.identifier + '/mailing/compose/to-group/' + props.mailToType, {
        method: "POST",
        body: {
            groupName: props.recipientIdentifier
        }
    });

    data.recipients = response.recipients;
    form.recipients = data.recipients.join(', ');
});

const errorMessage = ref(null)

const emit = defineEmits([
    'closeComposer',

]);

function close() {
    emit('closeComposer');
}


async function sendMail() {
    const response = await request('/api/v1/event/' + props.event.identifier + '/mailing/send', {
        method: "POST",
        body: {
            recipients: form.recipients,
            subject: form.subject,
            message: form.message,
        }
    });

    if (response.success) {
        close();
        toast.success(response.message)

    } else {
        errorMessage.value = response.message
        toast.error(response.message)
    }
}

const form = reactive({
    recipients: '',
    sendCopy: true,
    subject: '',
    message: '',
});
</script>

<template>
    <h2>E-Mail senden</h2>
    <div style="display: flex; flex-direction: column; gap: 12px;">
        <div>
            <label style="font-weight: bold">Empfänger*innen</label>
            <textarea v-model="form.recipients" placeholder="Senden an" style="width: 100%;" rows="3"></textarea>
        </div>
        <div>
            <label style="font-weight: bold">Betreff</label>
            <input type="text" v-model="form.subject" placeholder="Betreff" style="width: 100%;" />
        </div><br /><br />
        <div>
            <label style="font-weight: bold">Nachricht</label>
            <TextEditor v-model="form.message" />
        </div>
        <strong><ErrorText :message="errorMessage" /></strong>

    </div>

    <input type="button" @click="sendMail" value="Senden" class="" />

</template>

<style scoped>

</style>
