<template>
  <Fluid>
    <h1 class="text-xl font-bold mt-6">KS Video</h1>
    <div class="card flex mt-2 flex-col gap-4 w-full justify-center">
      <Stepper value="1" linear :loading="loadingStore.another_loading">
        <StepList>
          <Step value="1">Add video</Step>
          <Step value="2">Set parameters</Step>
          <Step value="3">Index video</Step>
        </StepList>
        <StepPanels>
          <StepPanel value="1" v-slot="{ activateCallback }">
            <div class="flex flex-col h-48">
              <FileUpload ref="fileUpload" :maxFileSize="1000000000000" chooseLabel="Select Video" class="p-button"
                style="width: 150px;" @select="onFileSelect" @remove="onFileRemove" :showUploadButton="false"
                :showCancelButton="false" v-model:files="selectedFile" :fileLimit="1"
                accept=".mp3,.mp4,.mkv,.flv,.mov,.ts">
                <template #empty>
                  <div class="flex items-center justify-center flex-col">
                    <i class="pi pi-cloud-upload !border-2 !rounded-full !p-8 !text-4xl !text-muted-color" />
                    <p class="mt-6 mb-0">Drag and drop the file you want to add to the knowledge base. Only audio and
                      video files are allowed.</p>
                  </div>
                </template>
              </FileUpload>
            </div>
            <div class="flex justify-between pt-6 mt-16">
              <Button label="Back to videos"
                :style="{ width: '150px', backgroundColor: '#9c9c9c', color: 'white', border: '1px grey' }"
                icon="pi pi-arrow-left" @click="router.push({ name: 'ks-video' })" />
              <Button label="Next" icon="pi pi-arrow-right" @click="activateCallback('2')" :disabled="!isFileSelected"
                style="width: 150px;" class="p-button" v-tooltip.top="!isFileSelected ? 'Please select a file' : ''" />
            </div>
          </StepPanel>
          <form @submit.prevent="submitForm" class="p-fluid">
            <StepPanel value="2" v-slot="{ activateCallback }">
              <div class="flex flex-col h-full">
                <Tabs class="mt-6" value="0">
                  <TabList>
                    <Tab value="0">Base</Tab>
                    <Tab value="1">Advanced</Tab>
                  </TabList>
                  <TabPanels>
                    <TabPanel value="0">
                      <div class="col-12 md:col-6 mb-4 mt-4">
                        <span class="p-float-label">
                          <label for="description">Video Description</label>
                          <i class="pi pi-info-circle text-violet-600 cursor-pointer"
                            v-tooltip="'A brief overview of the video'"></i>
                          <InputText id="description" type="text" v-model="formData.description" required
                            class="w-full" />
                        </span>
                      </div>
                      <div class="col-12 md:col-6 mb-4">
                        <span class="p-float-label">
                          <label for="type">File Type</label>
                          <i class="pi pi-info-circle text-violet-600 cursor-pointer"
                            v-tooltip="'Specify the type of file'"></i>
                          <InputText id="type" v-model="formData.type" required class="w-full" />
                        </span>
                      </div>
                      <div class="col-12 md:col-6 mb-4">
                        <span class="p-float-label">
                          <label for="ksProjectName">KS Project Name</label>
                          <InputText id="ksProjectName" v-model="userPrefStore.selectedProject.internal_name" required
                            class="w-full" :disabled="true" />
                        </span>
                      </div>
                      <div class="col-12 md:col-6 mb-4">
                        <span class="p-float-label">
                          <label for="ksApplicationName">KS Application Name</label>
                          <Dropdown id="ksApplicationName" v-model="formData.ksApplicationName"
                            :options="availableAppOptions" optionLabel="name" required class="w-full"></Dropdown>
                        </span>
                      </div>
                      <div class="col-12 md:col-6 mb-4">
                        <span class="p-float-label">
                          <label for="ksDocType">KS Document Type</label>
                          <i class="pi pi-info-circle text-violet-600 cursor-pointer"
                            v-tooltip="'Specify the type of video'"></i>
                          <Dropdown id="ksDocType" v-model="formData.ksDocType" :options="videoTypeOptions"
                            optionLabel="name" :required class="w-full"></Dropdown>
                        </span>
                      </div>
                      <div class="col-12 md:col-6 mb-4">
                        <span class="p-float-label">
                          <label for="ksDocSource">KS Document Source</label>
                          <i class="pi pi-info-circle text-violet-600 cursor-pointer"
                            v-tooltip="'Specify the video source. e.g, Retrieved from DevopsJ2Cloud Git Repository - CSV System Configuration '"></i>
                          <InputText id="ksDocSource" v-model="formData.ksDocSource" required class="w-full" />
                        </span>
                      </div>
                      <div class="col-12 md:col-6 mb-4 mt-4">
                        <span class="p-float-label">
                          <label for="language">Language</label>
                          <i class="pi pi-info-circle text-violet-600 cursor-pointer"
                            v-tooltip="'Define the language'"></i>
                          <Dropdown id="language" v-model="formData.language" :options="languageOptions"
                            optionLabel="name" required class="w-full" />
                        </span>
                      </div>
                    </TabPanel>
                    <TabPanel value="1">
                      <div class="col-12 md:col-6 mb-4 mt-4">
                        <span class="p-float-label">
                          <label for="numberOfChunkToEmbed">Number Chunks to Embed</label>
                          <i class="pi pi-info-circle text-violet-600 cursor-pointer"
                            v-tooltip="'Define the number of chunks to embed for RAG'"></i>
                          <InputNumber id="numberOfChunkToEmbed" v-model="formData.numberOfChunkToEmbed" required
                            class="w-full" :disabled="userPrefStore.user.role !== 'ADMIN'" />
                        </span>
                        <small v-if="errors.numberOfChunkToEmbed" class="text-red-500">
                          {{ errors.numberOfChunkToEmbed }}
                        </small>
                      </div>
                      <div class="col-12 md:col-6 mb-4 mt-4">
                        <span class="p-float-label">
                          <label for="chunkDurationInSeconds">Chunk duration in seconds</label>
                          <i class="pi pi-info-circle text-violet-600 cursor-pointer"
                            v-tooltip="'Define the chunk duration'"></i>
                          <InputNumber id="chunkDurationInSeconds" v-model="formData.chunkDurationInSeconds" required
                            class="w-full" :disabled="userPrefStore.user.role !== 'ADMIN'" />
                        </span>
                        <small v-if="errors.chunkDurationInSeconds" class="text-red-500">
                          {{ errors.chunkDurationInSeconds }}
                        </small>
                      </div>
                    </TabPanel>
                  </TabPanels>
                </Tabs>
              </div>
              <div class="flex justify-between pt-6">
                <Button label="Back"
                  :style="{ width: '150px', backgroundColor: '#9c9c9c', color: 'white', border: '1px grey' }"
                  icon="pi pi-arrow-left" @click="activateCallback('1')" />
                <Button label="Next" style="width: 150px;" class="p-button" icon="pi pi-arrow-right" iconPos="right"
                  @click="activateCallback('3')" :disabled="!isFormValid"
                  v-tooltip.top="!isFormValid ? 'Please fill in all fields' : ''" />
              </div>
            </StepPanel>
            <StepPanel value="3" v-slot="{ activateCallback }">
              <div class="flex flex-col mt-8 h-64">
                <p v-if="selectedFile" class="text-center">You can execute the indexing for the following file:</p>
                <p v-if="selectedFile" class="text-center">{{ selectedFile.name }}</p>
                <div class="flex justify-center mt-4">
                  <Button type="submit" label="Upload" :fluid="false" :disabled="uploadPercentage > 0"></Button>
                </div>
                <div class="flex justify-center mt-8 w-1/2 mx-auto" v-if="uploadPercentage > 0">
                  <div class="flex flex-col items-center gap-4 w-full">
                    <p class="text-center">Wait until the upload is completed. You will be automatically redirected.</p>
                    <ProgressBar :value="uploadPercentage" class="w-full" />
                  </div>
                </div>
              </div>
              <div class="flex justify-between pt-6">
                <Button label="Back"
                  :style="{ width: '150px', backgroundColor: '#9c9c9c', color: 'white', border: '1px grey' }"
                  icon="pi pi-arrow-left" @click="activateCallback('2')" />
              </div>
            </StepPanel>
          </form>
        </StepPanels>
      </Stepper>
    </div>
  </Fluid>
  <Dialog v-model:visible="showDialog" header="Confirm Overwrite" :modal="true">
    <p>The video "{{ selectedFile?.name }}" already exists with status "{{ existingVideo?.ingestionStatus }}". Do
      you want to overwrite it?</p>
    <template #footer>
      <Button label="Cancel" icon="pi pi-times" @click="cancelOverwrite" class="p-button" />
      <Button label="Overwrite" icon="pi pi-check" @click="confirmOverwrite" class="p-button-danger" />
    </template>
  </Dialog>
</template>

<script setup>
import axios from 'axios';
import Step from 'primevue/step';
import StepList from 'primevue/steplist';
import StepPanel from 'primevue/steppanel';
import StepPanels from 'primevue/steppanels';
import Stepper from 'primevue/stepper';
import { useToast } from 'primevue/usetoast';
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { KsVideoGroupStore } from '../../../stores/KsVideoGroupStore';
import { KsVideoStore } from '../../../stores/KsVideoStore';
import { LoadingStore } from '../../../stores/LoadingStore';
import { UserPrefStore } from '../../../stores/UserPrefStore';

const toast = useToast();
const route = useRoute();
const router = useRouter();
const userPrefStore = UserPrefStore();
const loadingStore = LoadingStore();
const ksVideoStore = KsVideoStore();
const ksVideoGroupStore = KsVideoGroupStore();
const required = ref([]);
const fileUploaded = ref(false);
const fileUpload = ref(null);
const selectedFile = ref(null);
const ingestionDialogVisible = ref(false);
const ksVideos = ref(null);
const showDialog = ref(false);
const existingVideo = ref(null);
const formDataToSend = ref(new FormData());
const groupDocType = ref('');
const uploadPercentage = ref(0);

const videoTypeOptions = ref([
  { name: 'Functional video', value: 'functional_video' },
  { name: 'Code Instruction video', value: 'code_instruction_video' },
  { name: 'Specification video', value: 'specification_video' },
  { name: 'Other', value: 'other_video' }
]);
const availableAppOptions = ref([
  { name: 'Cross', value: '' },
  ...userPrefStore.availableApp.map(app => ({ name: app.internal_name, value: app.internal_name }))
]);
const languageOptions = ref([
  { name: 'Italian', value: 'it-IT' },
  { name: 'English', value: 'en-US' },
  { name: 'French', value: 'fr-FR' },
  { name: 'German', value: 'de-DE' },
  { name: 'Spanish', value: 'es-ES' }
]);
const errors = ref({
  numberOfChunkToEmbed: "",
  chunkDurationInSeconds: "",
});

const formData = ref({
  description: '',
  type: '',
  ksProjectName: '',
  ksApplicationName: { name: 'Cross', value: '' },
  ksDocType: { name: 'Functional', value: 'functional' },
  ksDocSource: '',
  numberOfChunkToEmbed: 10,
  chunkDurationInSeconds: 600,
  language: { name: 'Italian', value: 'it-IT' }
});


const isFileSelected = computed(() => selectedFile.value !== null);

watch(
  () => formData.value.numberOfChunkToEmbed,
  (newValue) => validateField("numberOfChunkToEmbed", newValue, 5, 50),
);
watch(
  () => formData.value.chunkDurationInSeconds,
  (newValue) => validateField("chunkDurationInSeconds", newValue, 5, 900),
);


const validateField = (field, value, minvalue, maxvalue) => {
  if (value === null || value === undefined || value < minvalue || value > maxvalue) {
    errors.value[field] = "Value must be between " + minvalue + " and " + maxvalue;
  } else {
    errors.value[field] = "";
  }
};

const isFormValid = computed(() => {
  return (
    formData.value.description &&
    formData.value.type &&
    formData.value.ksApplicationName &&
    formData.value.ksDocType &&
    formData.value.ksDocSource &&
    !Object.values(errors.value).some((err) => err !== "")
  );
});

const onFileSelect = (event) => {
  if (event.files && event.files.length > 0) {
    selectedFile.value = event.files[0];
    formData.value.type = selectedFile.value.name.split('.').pop().toLowerCase();
    formData.value.description = selectedFile.value.name;
    fileUploaded.value = true;
  } else {
    selectedFile.value = null;
    fileUploaded.value = false;
  }

  toast.add({
    severity: 'success',
    summary: 'Success',
    detail: 'File uploaded successfully!',
    life: 3000
  });
};

onMounted(async () => {
  await updateVideos();
});

const updateVideos = async () => {
  ksVideoStore.fetchKsVideoByGroupId(route.params.groupId).then(() => {
    ksVideos.value = (ksVideoStore.ksVideo || []);
    //groupDocType.value = ksVideoGroupStore.ksVideoGroup?.ksDocType || ''
    console.log('ksVideos', ksVideos.value);
    //console.log('groupDocType', groupDocType.value);
  });
};

const onFileRemove = () => {
  selectedFile.value = null;
  toast.add({
    severity: 'success',
    summary: 'Success',
    detail: 'File removed successfully!',
    life: 3000
  });
};


const deleteRecord = (name) => {
  const videoToDelete = ksVideos.value.find(video => video.name === name);
  if (!videoToDelete) {
    console.error('Video not found');
    return;
  }

  const requestPayload = {
    ksDocumentId: videoToDelete.id,
    ksIngestionInfoId: videoToDelete.ingestionInfo.id,
    ksDocType: videoToDelete.ingestionInfo.metadata.ksDocType,
    ksDocSource: videoToDelete.ingestionInfo.metadata.ksDocSource,
    ksFileSource: videoToDelete.ingestionInfo.metadata.KsFileSource,
    ksApplicationName: videoToDelete.ingestionInfo.metadata.KsApplicationName,
  };

  axios.post('/fe-api/vector-store/deleteVideoRecords', requestPayload)
    .then(response => {
      console.log('Delete resource:', response.data)
    })
    .catch(error => {
      console.error('Error overwriting records: ', error)
      toast.add({ severity: 'error', summary: 'Error', detail: 'Error in Overwriting', life: 3000 });
    });

};

const submitForm = async () => {
  formDataToSend.value = new FormData(); // Reset del formData ogni volta

  if (selectedFile.value) {
    formDataToSend.value.append('file', selectedFile.value); // Aggiungi il file

    // Aggiungi i dati del fileUploadDTO
    formDataToSend.value.append('description', formData.value.description);
    formDataToSend.value.append('type', formData.value.type);
    formDataToSend.value.append('ksProjectName', userPrefStore.selectedProject.internal_name);
    formDataToSend.value.append('ksApplicationName', formData.value.ksApplicationName.value);
    formDataToSend.value.append('ksVideoGroupId', route.params.groupId);
    formDataToSend.value.append('ksDocType', formData.value.ksDocType.value);
    formDataToSend.value.append('ksDocSource', formData.value.ksDocSource);
    formDataToSend.value.append('numberOfChunkToEmbed', formData.value.numberOfChunkToEmbed);
    formDataToSend.value.append('chunkDurationInSeconds', formData.value.chunkDurationInSeconds);
    formDataToSend.value.append('language', formData.value.language.value);

    // Check if video with same name exists
    existingVideo.value = ksVideos.value?.find(video =>
      video.name.toLowerCase() === selectedFile.value.name.toLowerCase()
    );

    if (existingVideo.value) {
      showDialog.value = true;
      return;
    }
  }

  await uploadFile(formDataToSend.value);
};

const confirmOverwrite = async () => {
  showDialog.value = false;
  deleteRecord(selectedFile.value.name);
  await uploadFile(formDataToSend.value);
};

const cancelOverwrite = () => {
  showDialog.value = false;
};

const uploadFile = async (formDataToSend) => {
  try {
    const response = await axios.post('/upload_video', formDataToSend, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        uploadPercentage.value = percentCompleted;
        console.log(`Upload progress: ${percentCompleted}%`);
      }
    });

    toast.add({ severity: 'info', summary: 'Info', detail: 'Uploading done. Indexing will start in few seconds.', life: 3000 });

    router.push({ name: 'ks-video' });

  } catch (error) {
    console.error('Indexing failed:', error);
  }
};

</script>

<style scoped>
.pi-info-circle {
  margin-left: 6px;
  cursor: pointer;
}

.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  background-color: rgba(255, 255, 255, 0.8);
}
</style>
