<template>
        <div v-if="loading" class="flex justify-center">
            <ProgressSpinner style="width: 50px; height: 50px; margin-top: 50px" strokeWidth="3" fill="transparent"/>
        </div>
        <div v-else>
            <div class="flex items-center justify-between p-2">
            
             <!--   <Button
                    @click="back()" 
                    label="Load" 
                    class="flex items-center text-sm">
                        <ChevronLeftIcon name="chevron-left" class="w-4 h-5 text-white"/>        
                        <span>Back to Scenarios</span>
                    </Button> -->
            </div>
          
        </div>

        <div v-if="loading_data" class="flex justify-center">
            <ProgressSpinner style="width: 30px; height: 30px; margin: 30px" strokeWidth="6" fill="transparent"/>
        </div>
        <div v-if="data_loaded">
            <!-- <div class="box p-4 border rounded-md shadow-sm" style="background-color: #f3f3f3;">
                    <div v-for="(input, index) in inputs" :key="index" class="input-container">
                        <div class="input-wrapper">
                            <span class="font-bold">{{ index.replace(/_/g, ' ').replace(/\b\w/g, char => char.toUpperCase()) }}:</span>
                            <span>{{ input }}</span>
                        </div>
                    </div>
            </div> -->

            <Panel class="mt-6">
                <template #header>
                <div class="flex items-center gap-2">
                    <span class="font-bold">Execution Input for ID {{execution_id}}</span>
                    <div v-if="rating!=null" class="flex justify-end">
                        <Rating
                      
                        :modelValue="rating"
                        :stars="5"
                        
                        :readonly="true"
                    />
                    </div>
                    <div v-else class="flex justify-end">
                        <Rating
                       
                        :modelValue="rating"
                        :stars="5"
                       
                        @change="updateRating($event)"
                        />

                        </div>  
                   
                </div>
                </template>
               
                <div class="box p-4 border rounded-md shadow-sm" style="background-color: white;">
                    <div v-for="(input, index) in inputs" :key="index" class="input-container">
                        <div class="input-wrapper">
                            <span class="font-bold">{{ index.replace(/_/g, ' ').replace(/\b\w/g, char => char.toUpperCase()) }}:</span>
                            <span>{{ input }}</span>
                        </div>
                    </div>
            </div>
            </Panel>

            <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">
                    <Button severity="secondary" rounded @click="openDebug" v-tooltip.left="'View code'">
                        <i class="pi pi-code"></i>
                    </Button>
                    </div>
                </template>
                
                <div class="card flex flex-col gap-4 w-full">
                    <div v-if="scenario.outputType == 'ciaOutput'">
                        <ChangeImpactOutputViewer :scenario_output="scenario_output" />                       
                    </div>
                    <div v-else>
                        <MdPreview class="editor" v-model="scenario_output" language="en-US"  />
                    </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>
        </div>
</template>

<script setup>

import ChangeImpactOutputViewer from '@/components/ChangeImpactOutputViewer.vue';
import axios from 'axios';
import JsonEditorVue from 'json-editor-vue';
import { MdPreview } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import ProgressSpinner from 'primevue/progressspinner';
import { useToast } from 'primevue/usetoast';
import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ScenarioService } from '../../service/ScenarioService.js';
import { ScenarioExecutionStore } from '../../stores/ScenarioExecutionStore.js';

const router = useRouter();
const route = useRoute();
const value = ref('');
const scenario = ref({});
const scenario_output = ref(null);
const loading = ref(false);
const data_loaded = ref(false);
const loading_data = ref(false);
const formData = ref({});
const exec_id = ref(null);
const exec_scenario = ref({});
const debug_modal = ref(false);
const rating = ref(null);
const scenario_execution_store = ScenarioExecutionStore();
const execution = scenario_execution_store.getSelectedExecScenario;
const execution_id = ref(null)
const inputs = ref(null);
const toast = useToast();   


onMounted(() => {
    if (execution){
        console.log("scenario id: ", execution);
        execution_id.value = execution.id
        console.log("execution_id: ",execution_id)
    }else{
        const url = window.location.href;
        execution_id.value = (new URL(url)).searchParams.get('id')
        console.log(execution_id.value)
    }
    retrieveScenarioExec(execution_id.value)
});

const retrieveScenarioExec = (id) => {
    //const id = execution_id.value.id;
    loading.value = true

    axios.get('/execution?id=' + id )
        .then(response => {
            loading.value = false
            scenario.value  = response.data.scenario
            exec_scenario.value = response.data
            data_loaded.value = true;
            rating.value = response.data.rating
            scenario_output.value = response.data.execSharedMap.scenario_output;
            exec_id.value = response.data.scenarioExecution_id
            inputs.value = response.data.scenarioExecutionInput.inputs
        });
};

async function updateRating(newRating) {
    
    loading_data.value = true;
    ScenarioService.updateScenarioExecRating(execution_id.value,newRating.value).then((response) => {

        console.log('response:', response);
        if (response.data === "OK") {
            rating.value = newRating.value;
            console.log('Rating aggiornato con successo:', response.data);
            toast.add({
                severity: 'success', // Tipo di notifica (successo)
                summary: 'Successo', // Titolo della notifica
                detail: 'Rating updated with success.', // Messaggio dettagliato
                life: 3000 // Durata della notifica in millisecondi
            });
        } else {
            console.error('Errore nell\'aggiornamento del rating', response.data);
            toast.add({
             severity: 'error', // Tipo di notifica (errore)
             summary: 'Errore', // Titolo della notifica
             detail: 'Error updating rating. Try later.', // Messaggio dettagliato
             life: 3000 // Durata della notifica in millisecondi
         });
        }
    }).catch((error) => {
        console.error('Errore durante la chiamata al backend:', error);
    }).finally(() => {
        loading_data.value = false;
    });
    

}

   

    
const back = () => {
    router.push({ name: 'scenario-list'});
}

const openDebug = () => {
    debug_modal.value = true
}
</script>

<style scoped>
    .input-container {
        margin-bottom: 1em;
    }

    .input-wrapper {
        display: flex;
        align-items: center; 
        gap: 0.5em; 
        margin-top: 10px;
    }

    .full-width-input {
        width: 100%;
    }


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

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