<script setup>
import ChangeImpactOutputViewer from '@/components/ChangeImpactOutputViewer.vue';
import { ScenarioService } from '@/service/ScenarioService';
import { ScenarioExecutionStore } from '@/stores/ScenarioExecutionStore';
import JsonEditorVue from 'json-editor-vue';
import { marked } from 'marked';
import { useToast } from 'primevue/usetoast';
import { computed, ref } from 'vue';
import MarkdownViewer from './MarkdownViewer.vue';

const props = defineProps({
    scenario: {
        type: Object,
        required: true
    },
    scenarioOutput: {
        type: String,
        default: ''
    },
    execId: {
        type: [String, Number],
        default: null
    },
    errorMessage: {
        type: String,
        default: ''
    },
    erroredExecution: {
        type: Boolean,
        default: false
    }
});

const scenarioExecutionStore = ScenarioExecutionStore();
const toast = useToast();

const rating = ref(0);
const debug_modal = ref(false);
const exec_scenario = ref({});
const fileContent = ref('');
const fileType = ref('');

const localScenarioOutput = computed(() => props.scenarioOutput);

const openDebug = async () => {
    try {
        const resp = await scenarioExecutionStore.getScenarioExecution(props.execId);
        exec_scenario.value = resp;
        debug_modal.value = true;
    } catch (error) {
        console.error('Error opening debug:', error);
    }
};

const updateRating = async (newRating) => {
    try {
        const response = await ScenarioService.updateScenarioExecRating(props.execId, newRating.value);

        if (response.data === 'OK') {
            rating.value = newRating.value;
            toast.add({
                severity: 'success',
                summary: 'Success',
                detail: 'Rating updated with success.',
                life: 3000
            });
        } else {
            console.error('Error during rating update', response.data);
            toast.add({
                severity: 'error',
                summary: 'Error',
                detail: 'Error updating rating. Try later.',
                life: 3000
            });
        }
    } catch (error) {
        console.error('Error during backend call:', error);
        toast.add({
            severity: 'error',
            summary: 'Error',
            detail: 'Error updating rating.',
            life: 3000
        });
    }
};

const downloadFile = () => {
    try {
        const base64String = props.scenarioOutput;
        const byteCharacters = atob(base64String);
        const byteNumbers = Array.from(byteCharacters, (char) => char.charCodeAt(0));
        const byteArray = new Uint8Array(byteNumbers);
        const blob = new Blob([byteArray]);

        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'sf_document-' + props.execId + '.docx';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    } catch (error) {
        console.error('Error during file download:', error);
    }
};

const showFileContent = (base64String, type) => {
    try {
        const binaryString = atob(base64String);
        const binaryLength = binaryString.length;
        const bytes = new Uint8Array(binaryLength);

        for (let i = 0; i < binaryLength; i++) {
            bytes[i] = binaryString.charCodeAt(i);
        }

        const textContent = new TextDecoder().decode(bytes);

        if (type === 'MARKDOWN') {
            fileContent.value = marked(textContent);
        } else if (type === 'JSON') {
            const jsonObject = JSON.parse(textContent);
            fileContent.value = JSON.stringify(jsonObject, null, 2);
        } else {
            fileContent.value = 'Unsupported file type.';
        }
    } catch (error) {
        fileContent.value = 'Error while decoding or parsing file.';
        console.error(error);
    }
};

defineExpose({
    showFileContent,
    fileType
});
</script>

<template>
    <Panel class="mt-6">
        <template #header>
            <div class="flex items-center gap-2">
                <span class="font-bold">Workflow Response</span>
            </div>
        </template>

        <template #icons>
            <div class="flex justify-end">
                <div class="flex">
                    <Rating :modelValue="rating" :stars="5" @change="updateRating($event)" />
                </div>

                <div>
                    <Button severity="secondary" rounded @click="openDebug" v-tooltip.left="'View execution info'">
                        <i class="pi pi-code"></i>
                    </Button>
                </div>
            </div>
        </template>

        <div v-if="erroredExecution" class="card flex flex-col gap-4 w-full">
            <div v-if="errorMessage">
                <p class="text-red-500 font-bold">Error: {{ errorMessage }}</p>
            </div>
            <div v-else>
                <p class="text-red-500 font-bold">Error: Execution failed.</p>
            </div>
        </div>

        <div v-else class="card flex flex-col gap-4 w-full">
            <div v-if="scenario.outputType == 'ciaOutput'">
                <ChangeImpactOutputViewer :scenario_output="scenarioOutput" />
            </div>

            <div v-else-if="scenario.outputType == 'file'">
                <Button icon="pi pi-download" label="Download File" class="p-button-primary" @click="downloadFile" />
            </div>

            <div v-else>
                <div v-if="fileType == 'FILE'">
                    <ul>
                        <li class="file-item">
                            sf_document-{{ execId }}
                            <Button icon="pi pi-download" class="p-button-text p-button-sm" label="Download" @click="downloadFile()" />
                        </li>
                    </ul>
                </div>
                <div v-else-if="fileType == 'MARKDOWN'">
                    <div v-html="fileContent" class="markdown-content"></div>
                </div>
                <div v-else-if="fileType == 'JSON'">
                    <pre>{{ fileContent }}</pre>
                </div>
                <div v-else>
                    <MarkdownViewer class="editor" :modelValue="localScenarioOutput" background-color="white" padding="20px" />
                </div>
            </div>
        </div>
    </Panel>

    <Dialog v-model:visible="debug_modal" maximizable modal :header="scenario.name" :style="{ width: '75%' }" :breakpoints="{ '1199px': '75vw', '575px': '90vw' }">
        <div class="flex">
            <div class="card flex flex-col gap-4 w-full">
                <JsonEditorVue v-model="exec_scenario" />
            </div>
        </div>
    </Dialog>
</template>

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

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

/* Removed pre and .markdown-content styles - handled by MarkdownViewer component */

.file-item {
    display: flex;
    align-items: center;
    gap: 1rem;
}
</style>
