<template>
    <div>
        <!-- 툴바 HTML -->
        <div id="toolbar">
            <select class="ql-font" v-model="font">
                <option value="nanum-gothic">나눔고딕</option>
                <option value="d2coding">d2coding</option>
                <option value="consolas">consolas</option>
                <option value="serif">Serif</option>
                <option value="monospace">Monospace</option>
            </select>

            <select class="ql-size" v-model="fontSize">
                <option value="12px">12px</option>
                <option value="14px">14px</option>
                <option value="16px" selected>16px</option>
                <option value="18px">18px</option>
                <option value="24px">24px</option>
                <option value="32px">32px</option>
                <option value="48px">48px</option>
            </select>

            <button class="ql-bold">B</button>
            <button class="ql-italic">I</button>
            <button class="ql-underline">U</button>

            <button class="ql-header" value="1">H1</button>
            <button class="ql-header" value="2">H2</button>
            <button class="ql-header" value="3">H3</button>
            <button class="ql-header" value="4">H4</button>
            <button class="ql-header" value="5">H5</button>
            <button class="ql-header" value="6">H6</button>

            <button class="ql-list" value="ordered">OL</button>
            <button class="ql-list" value="bullet">UL</button>

            <button class="ql-align" value="">Left</button>
            <button class="ql-align" value="center">Center</button>
            <button class="ql-align" value="right">Right</button>
            <button class="ql-align" value="justify">Justify</button>

            <button class="ql-link">Link</button>
            <button class="ql-image">Image</button>
            <button class="ql-blockquote">Blockquote</button>
            <button class="ql-code-block">Code Block</button>
        </div>
        <!-- 에디터가 표시될 div -->
        <div ref="editor"></div>

        <!-- Alert 메시지 표시 -->
        <div class="invalid-feedback" :class="isAlert ? 'd-block' : ''">내용을 확인해주세요.</div>   
    </div>
</template>

<script setup>
import Quill from 'quill';
import 'quill/dist/quill.snow.css';
import { onMounted, ref, watch, defineEmits, defineProps } from 'vue';
import $api from '@api';
const props = defineProps({
    isAlert: {
        type: Boolean,
        default: false,
    },
});
const editor = ref(null);
const font = ref('nanum-gothic');
const fontSize = ref('16px');
const emit = defineEmits(['update:data']);
onMounted(() => {
    const Font = Quill.import('formats/font');
    Font.whitelist = ['nanum-gothic', 'd2coding', 'consolas', 'serif', 'monospace'];
    Quill.register(Font, true);

    const Size = Quill.import('attributors/style/size');
    Size.whitelist = ['12px', '14px', '16px', '18px', '24px', '32px', '48px'];
    Quill.register(Size, true);

    const quillInstance = new Quill(editor.value, {
        theme: 'snow',
        placeholder: '내용을 입력해주세요...',
        modules: {
            toolbar: {
                container: '#toolbar',
            },
            syntax: true,
        },
    });
    quillInstance.format('font', font.value);
    quillInstance.format('size', fontSize.value);

    quillInstance.on('text-change', () => {
        const delta = quillInstance.getContents();  // Get Delta format
        emit('update:data', delta);
    });

    watch([font, fontSize], () => {
        quillInstance.format('font', font.value);
        quillInstance.format('size', fontSize.value);
    });

    // Handle image upload
    let imageUrls = new Set();
    quillInstance.getModule('toolbar').addHandler('image', () => {
        selectLocalImage();
    });
    quillInstance.on('text-change', (delta, oldDelta, source) => {
        // Emit Delta when content changes
        emit('update:data', quillInstance.getContents());
        delta.ops.forEach(op => {
            if (op.insert && typeof op.insert === 'object' && op.insert.image) {
                const imageUrl = op.insert.image;
                imageUrls.add(imageUrl);
            } else if (op.delete) {
                checkForDeletedImages();
            }
        });
    });
    async function selectLocalImage() {
        const input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'image/*');
        input.click();
        input.onchange = () => {
            const file = input.files[0];
            if (file) {
                const formData = new FormData();
                formData.append('file', file);

                uploadImageToServer(formData).then(serverImageUrl => {
                    const baseUrl = $api.defaults.baseURL.replace(/api\/$/, '');
                    const fullImageUrl = `${baseUrl}${serverImageUrl.replace(/\\/g, '/')}`;

                    const range = quillInstance.getSelection();
                    quillInstance.insertEmbed(range.index, 'image', fullImageUrl);

                    imageUrls.add(fullImageUrl);
                }).catch(e => {
                    toastStore.onToast('잠시후 다시 시도해주세요.', 'e');
                });
            }
        };
    }
    async function uploadImageToServer(formData) {
        try {
            const response = await $api.post('quilleditor/upload', formData, { isFormData: true });
            const imageUrl = response.data.data;
            return imageUrl;
        } catch (error) {
            toastStore.onToast('잠시후 다시 시도해주세요.', 'e');
            throw error;
        }
    }
    function checkForDeletedImages() {
        const editorImages = document.querySelectorAll('#editor img');
        const currentImages = new Set(Array.from(editorImages).map(img => img.src));

        imageUrls.forEach(url => {
            if (!currentImages.has(url)) {
                imageUrls.delete(url);
            }
        });
    }
});
</script>
<style>
@import 'quill/dist/quill.snow.css';
.ql-editor {
    min-height: 300px;
    font-family: 'Nanum Gothic', sans-serif;
}
</style>
