<template>
    <div className="card">
        <Dialog v-model:visible="execScenarioDialogVisible" modal :header="execScenario.name" :style="{ width: '70rem' }">
            <MdScenarioExctuotionDialog :scenario="execScenario" @add="addFromDialog"/>
        </Dialog>
        <ContextMenu ref="menu" :model="items" :style="{'white-space':'nowrap', 'width': 'auto'}"/>
        <Dialog v-model:visible="execHermioneDialogVisible" modal :header="modalTitle" :style="{ width: '70rem' }">
            <div v-if="askDialog" class="card flex flex-col gap-4 p-1">
                <div class="flex flex-col gap-2">
                    <Textarea id="question" type="text" placeholder="Write a Question" v-model="userQuestion" />
                </div>    
                <div class="flex justify-center">
                    <Button label="Submit" @click="askHermione()" class=""/>
                </div>
            </div>

            <div class="flex justify-center items-center">
                <ProgressSpinner v-if="loadingData" style="width: 50px; height: 50px" strokeWidth="8" fill="transparent"
                animationDuration=".5s" aria-label="Custom ProgressSpinner" />
            </div>

            <div v-if="dataLoaded" class="card flex flex-col gap-4 p-1">       
                <div class="flex items-center gap-2 p-0">
                    <button class="p-button p-button-primary" @click="addFromDialog(response)">Add to Canvas</button>
                </div>     
                <div class="flex mt-2">
                    <!-- <Editor v-model="response" editorStyle="height: 320px; width: 930px" /> -->
                    <MdPreview class="editor" v-model="response" language="en-US" />
                </div>
            </div> 
        </Dialog>
        <MdEditor class="editor" v-model="content" language="en-US" ref="editor"  @contextmenu="onRightClick" previewTheme="github" :toolbars="toolbars">     
            <template #defToolbars>
                <Mark />
                <Emoji />
                <ExportPDF :modelValue="content" height="700px" />
            </template>

        </MdEditor>
        
    </div>
</template>

<script setup>
    import { ScenarioService } from '@/service/ScenarioService.js';
import MdScenarioExctuotionDialog from '@/views/pages/canvas/MdScenarioExecutionDialog.vue';
import { Emoji, ExportPDF, Mark } from '@vavt/v3-extension';
import '@vavt/v3-extension/lib/asset/style.css';
import axios from 'axios';
import { MdEditor, MdPreview } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import { computed, onMounted, ref} from 'vue';
import { ScenarioStore } from '@/stores/ScenarioStore';
import { UserPrefStore } from '@/stores/UserPrefStore';

    const menu = ref();
    const content = ref('# Welcome to WizardAI Canvas.... \n- Right-click to execute one of the available scenarios or ask general questions to Workflow.\n- Select text and right-click to summarize or rewrite it.');
    const scenario_store = ScenarioStore();
    const userPrefStore = UserPrefStore();
    const scenarios = ref([]);
    const items = ref([]);
    const execScenarioDialogVisible = ref(false);
    const execScenario = ref({name:""});
    const editor = ref();
    const execHermioneDialogVisible = ref(false)
    const modalTitle = ref('')
    const askDialog = ref(false)
    const loadingData = ref(false)
    const dataLoaded = ref(false)
    const response = ref(null)
    const userQuestion = ref('')


    const addFromDialog = (data) => {
        console.log(data);
        execScenarioDialogVisible.value = false;
        execHermioneDialogVisible.value = false;

         editor.value.insert((selectedText) => {
            return {
            targetValue: data,
            select: true,
            deviationStart: 0,
            deviationEnd: 0,
            };
        });
    }

    const onRightClick = async (event) => {
        if(editor.value.getSelectedText().length > 0) {
            items.value=[
                {label: 'Summarize',icon: 'pi pi-language', command:()=>openEditorAssistant(editor.value.getSelectedText(), "summarize")},
                {label: 'Rewrite', icon: 'pi pi-language', command:()=>openEditorAssistant(editor.value.getSelectedText(), "rewrite")}
            ]
        }else {
            items.value=[
                {label: 'Ask Workflow', icon: 'pi pi-language', command:()=>openAskDialog()},
                {separator: true}
        ]
            if (scenarioMenuItems().length > 0) {
                items.value.push({label: 'Execute Scenario', icon: 'pi pi-volume-up', items: scenarioMenuItems()})
            }
        }     
        menu.value.show(event);
    };

    function scenarioMenuItems() { 
        const scenario_items = [];
        scenario_store.filteredScenariosCanvas.forEach(scenario => {
            if (scenario.canvasEnabled) {
                scenario_items.push({
                    label: scenario.name,
                    icon: 'pi pi-wrench',
                    command: () => {
                        executeScenario(scenario);
                    }
                });
            }
        });
        return scenario_items;
    };





    const executeScenario = (scenario) => {
        console.log(scenario.id);
        execScenarioDialogVisible.value = true;
        execScenario.value = scenario;
    }

    
    const openAskDialog = () => {
        execHermioneDialogVisible.value = true;
        askDialog.value = true
        dataLoaded.value = false
        modalTitle.value = "Ask Workflow"
        userQuestion.value = ''
    }

    const openEditorAssistant = (text, action) => {
        execHermioneDialogVisible.value=true
        modalTitle.value = "Editor Assistant"
        askDialog.value = false 
        loadingData.value = true
        dataLoaded.value = false

        if (action === "rewrite") {
            rephraseText(text)
        } else {
            summarizeText(text)
        }
    }

    const rephraseText = (text) => {
        const input = {
            input: text
        }
        console.log("INPUT: ", input);

        axios.post("/rephrase", input).then(resp => {
            console.log("RESPONSE: ", resp.data);
            response.value = resp.data.stringOutput
            loadingData.value = false
            dataLoaded.value = true
        })
        .catch(error => {
            console.error('Error during the request:', error);
        });
    };

    const summarizeText = (text) => {
        const input = {
            input: text
        }
        console.log("INPUT: ", input);

        axios.post("/summarize", input).then(resp => {
            console.log("RESPONSE: ", resp.data);
            response.value = resp.data.stringOutput
            loadingData.value = false
            dataLoaded.value = true
        })
        .catch(error => {
            console.error('Error during the request:', error);
        });
    };

    const askHermione = () => {
        const input = {
            input: userQuestion.value
        }
        console.log("INPUT: ", input);

        loadingData.value = true
        askDialog.value = false
        
        axios.post("/askHermione", input).then(resp => {
            console.log("RESPONSE: ", resp.data);
            response.value = resp.data.stringOutput
            loadingData.value = false
            dataLoaded.value = true
        })
        .catch(error => {
            console.error('Error during the request:', error);
        });
    };

    onMounted(() => {
        userPrefStore.fetchUserData().then(() => {
                scenario_store.fetchScenariosCross();
                scenario_store.fetchScenarios();
                if(userPrefStore.getSelApp != null){
                    scenario_store.fetchApplicationScenarios();
                }

            });
        scenarioMenuItems();
    });




    const toolbars = ref([
        'bold',
        'underline',
        'italic',
        'strikeThrough',
        '-',
        'title',
        'sub',
        'sup',
        'quote',
        'unorderedList',
        'orderedList',
        'task',
        '-',
        'codeRow',
        'code',
        'link',
        'image',
        'table',
        'mermaid',
        'katex',
        0,
        1,
        2,
        3, 
        '-',
        'revoke',
        'next',
        'save',
        '=',
        'prettier',
        'preview',
        'previewOnly',
        'htmlPreview'
        ]);
</script>

<style >

.editor ol {
    list-style-type: decimal !important;
}

.editor ul {
    list-style-type: disc !important;
}
</style>