<template>
	<Toast />
	<ConfirmPopup></ConfirmPopup>
	<div>
		<DataTable v-model:filters="filters" v-model:expandedRows="expandedRows" @rowExpand="onRowExpand"
			@rowCollapse="onRowCollapse" :value="ksVideos" :loading="loadingStore.loading_exectuion" :paginator="true"
			:rows="10"
			paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
			currentPageReportTemplate="Showing {first} to {last} of {totalRecords} records"
			:rowsPerPageOptions="[10, 15, 20, 50, 100]" dataKey="id" :rowHover="true" rowGroupMode="subheader"
			:sortOrder="1" filterDisplay="menu"
			:globalFilterFields="['ingestionInfo.metadata.KsApplicationName', 'ingestionInfo.metadata.KsFileSources', 'ingestionInfo.metadata.KsDocSource', 'ingestionStatus', 'ingestionDateFormat']"
			tableStyle="min-width: 70rem" removableSort>
			<template #header>
				<div class="flex items-center justify-between gap-8 p-6 ">
					<div class="flex flex-col">
						<span class="text-xl font-bold">Knowledge Source Videos</span>
						<span class="text-xl mt-2">{{ groupName }}</span>
					</div>
					<div class="flex items-center gap-2 flex-grow">
						<IconField class="flex-grow">
							<InputIcon>
								<i class="pi pi-search" />
							</InputIcon>
							<InputText v-model="filters['global'].value" placeholder="Search..." />
						</IconField>
					</div>
					<Button icon="pi pi-plus" rounded raised @click="newKsVideo()" v-tooltip.left="'Add New Video'"
						class="mr-2 p-button-sm" />
					<!--<Button icon="pi pi-check-circle" rounded raised @click="startlngestion()"
						v-tooltip.left="'Start All Videos Ingestion'" class="mr-8 p-button-sm"
						:disabled="allVideosIngested" :class="{ 'p-button': allVideosIngested }" />-->
				</div>
			</template>
			<template #empty>No Records found</template>
			<Column field="ingestionStatus" header="Status" sortable>
				<template #body="slotProps">
					<Tag v-tooltip="slotProps.data.ingestionMessage" :value="slotProps.data.ingestionStatus"
						:severity="getStatus(slotProps.data)" />
				</template>
				<template #filter="{ filterModel, filterCallback }">
					<Select v-model="filterModel.value" @change="filterCallback()" :options="statuses"
						placeholder="Select One" style="min-width: 12rem" :showClear="true">
						<template #option="{ option }">
							<Tag :value="option" :severity="getStatus({ ingestionStatus: option })" />
						</template>
					</Select>
				</template>
			</Column>
			<Column field="ingestionInfo.metadata.KsFileSource" header="FileName" sortable>
				<template #body="{ data }">
					<span>
						<i :class="getFileIcon(data.fileName)" class="mr-2"></i>
						{{ data.fileName }}
					</span>
				</template>
				<template #filter="{ filterModel, filterCallback }">
					<InputText v-model="filterModel.value" type="text" @input="filterCallback()"
						placeholder="Search by File Name" />
				</template>
			</Column>
			<Column field="ingestionInfo.metadata.KsApplicationName" header="ApplicationName" sortable
				style="min-width: 12rem">
				<template #body="{ data }">
					{{ data.ingestionInfo.metadata.KsApplicationName }}
				</template>
				<template #filter="{ filterModel, filterCallback }">
					<InputText v-model="filterModel.value" type="text" @input="filterCallback()"
						placeholder="Search by File" />
				</template>
			</Column>
			<Column field="ingestionInfo.metadata.KsDoctype" header="DocType" sortable style="min-width: 12rem">
				<template #body="{ data }">
					{{data.ingestionInfo.metadata.KsDoctype.replace(/_/g, ' ').replace(/\b\w/g, char =>
						char.toUpperCase())}}
				</template>
				<template #filter="{ filterModel, filterCallback }">
					<InputText v-model="filterModel.value" type="text" @input="filterCallback()"
						placeholder="Search by File" />
				</template>
			</Column>
			<Column header="Date" filterField="ingestionDateFormat" dataType="date" style="min-width: 10rem">
				<template #body="{ data }">
					{{ formatDate(data.ingestionDate) }}
				</template>
				<template #filter="{ filterModel }">
					<DatePicker v-model="filterModel.value" dateFormat="mm/dd/yy" placeholder="mm/dd/yyyy"
						@change="updateFilterModel" />
				</template>
			</Column>
			<Column field="id" header="Actions" style="width: 10rem" class="text-center">
				<template #body="slotProps">
					<div class="flex justify-center items-center space-x-3">

						<Button type="button" icon="pi pi-play" rounded
							@click="startIndividualngestion(slotProps.data.id)" v-tooltip.left="'Start video indexing'"
							:disabled="slotProps.data.ingestionStatus === 'INGESTED' || slotProps.data.ingestionStatus == 'IN PROGRESS' || slotProps.data.ingestionStatus == 'INGESTING' || slotProps.data.ingestionStatus == 'INGESTION_QUEUE'"
							:class="{ 'p-button': slotProps.data.ingestionStatus === 'INGESTED' }"></Button>
						<Button type="button" icon="pi pi-trash" rounded
							@click="(slotProps.data.ingestionStatus === 'LOADED' || slotProps.data.ingestionStatus === 'ERROR') ? deleteLoadedRecord(slotProps.data.id) : confirmDeleteFromVectorStore(slotProps.data.id)"
							v-tooltip.left="'Delete the ingested Record'"
							:disabled="(slotProps.data.ingestionStatus !== 'INGESTED' && slotProps.data.ingestionStatus !== 'LOADED' && slotProps.data.ingestionStatus !== 'ERROR') || slotProps.data.ingestionStatus == 'IN PROGRESS'"
							:class="{ 'mr-2 p-button': slotProps.data.ingestionStatus !== 'INGESTED' && slotProps.data.ingestionStatus !== 'LOADED' }"></Button>

						<Button type="button" icon="pi pi-search" rounded @click="openSimilaritySearch(slotProps.data)"
							v-tooltip.left="'Similarity Search'"
							:disabled="slotProps.data.ingestionStatus !== 'INGESTED' || slotProps.data.ingestionStatus == 'IN PROGRESS'"
							:class="{ 'mr-2 p-button': slotProps.data.ingestionStatus !== 'INGESTED' }"></Button>
						<Button type="button" icon="pi pi-download" rounded @click="downloadFile(slotProps.data)"
							v-tooltip.left="'Download file'" class="mr-2 p-button"></Button>
						<!-- <Button type="button" icon="pi pi-play" rounded @click="playVideo(slotProps.data)"
							v-tooltip.left="'Play Video'" class="mr-2 p-button"></Button> -->
					</div>
				</template>
			</Column>

		</DataTable>
		<!-- <Dialog v-model:visible="isVideoPlayerVisible" :header="selectedVideo?.fileName || 'Video Player'" :modal="true"
			:closable="true" :style="{ width: '80vw' }">
			<video v-if="selectedVideo" :src="selectedVideo.filePath" controls autoplay style="width: 100%;"></video>
		</Dialog> -->
	</div>
</template>

<script setup>
import { FilterMatchMode, FilterOperator } from '@primevue/core/api';
import axios from 'axios';
import moment from 'moment';
import { useConfirm } from "primevue/useconfirm";
import { useToast } from 'primevue/usetoast';
import { onMounted, onUnmounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import Button from 'primevue/button';
import Column from 'primevue/column';
import DataTable from 'primevue/datatable';
import DatePicker from 'primevue/datepicker';
import Dialog from 'primevue/dialog';
import InputText from 'primevue/inputtext';
import Select from 'primevue/select';
import Tag from 'primevue/tag';
import { KsVideoGroupService } from '../../../service/KsVideoGroupService';
import { KsVideoService } from '../../../service/KsVideoService';
import { KsVideoStore } from '../../../stores/KsVideoStore';
import { LoadingStore } from '../../../stores/LoadingStore';
import { UserPrefStore } from '../../../stores/UserPrefStore';

const route = useRoute();
const expandedRows = ref([]);
const router = useRouter()
const ksVideos = ref(null);
const loading = ref(true);
const toast = useToast();
const confirm = useConfirm();
const groupName = ref('');

//const ingestionDialogVisible = ref(false);
const ingestionResult = ref('');
const filters = ref();
const userPrefStore = UserPrefStore();
const ksVideoStore = KsVideoStore();
const loadingStore = LoadingStore();
const fe_status = ref('');
let updateTimer = null; // Variabile per memorizzare l'ID del timer

const isVideoPlayerVisible = ref(false);
const selectedVideoUrl = ref(null);

const playVideo = async (video) => {
	try {
		// 1) Scarica il video come arraybuffer o blob
		const response = await KsVideoService.downloadKsVideo(video)
		// 2) Leggi il content-type dinamico
		const contentType = response.headers['content-type'] || 'video/mp4'
		// 3) Crea il blob
		const blob = new Blob([response.data], { type: contentType })
		// 4) Crea e registra l'ObjectURL
		const url = window.URL.createObjectURL(blob)
		blobUrls.add(url)
		// 5) Mostra il player
		selectedVideoUrl.value = url
		isVideoPlayerVisible.value = true

	} catch (err) {
		console.error('Error while preparing video for playback:', err)
		toast.add({
			severity: 'error',
			summary: 'Playback Error',
			detail: 'Impossibile caricare il video.',
			life: 3000
		})
	}
}

const initFilters = () => {
	filters.value = {
		global: { value: null, matchMode: FilterMatchMode.CONTAINS },
		id: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.EQUALS }] },
		'ingestionInfo.metadata.KsApplicationName': { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.STARTS_WITH }] },
		'ingestionInfo.metadata.KsFileSource': { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.STARTS_WITH }] },
		'ingestionInfo.metadata.KsDocSource': { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.STARTS_WITH }] },
		ingestionDateFormat: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.DATE_IS }] },
		ingestionStatus: { operator: FilterOperator.OR, constraints: [{ value: null, matchMode: FilterMatchMode.EQUALS }] }
	};
};

initFilters();

const statuses = ref(['NEW', 'LOADED', 'INGESTED', 'FAILED', 'ERROR', 'INGESTION_QUEUE', 'INGESTING']); // Add your statuses here

onMounted(() => {
	userPrefStore.fetchUserData().then(() => {
		KsVideoGroupService.getVideoGroupById(route.params.groupId).then(response => {
			groupName.value = response.data.name;
		});
		updateVideos();
		updateTimer = setInterval(() => {
			updateVideos();
		}, 5000);
	});
});

onUnmounted(() => {
	if (updateTimer) {
		clearInterval(updateTimer); // Cancella il timer quando il componente viene distrutto
		updateTimer = null;
	}
});

const onRowExpand = (event) => {
	console.log("Row expanded:", event.data);
};

const onRowCollapse = (event) => {
	console.log("Row collapsed:", event.data);
};


function updateVideos() {
	ksVideoStore.fetchKsVideoByGroupId(route.params.groupId).then(() => {
		ksVideos.value = getCustomDatewithAllResponse();
	});
};

const getCustomDatewithAllResponse = () => {
	return [...(ksVideoStore.ksVideo || [])].map((d) => {
		d.ingestionDateFormat = new Date(d.ingestionDateFormat);
		return d;
	});
};


const getStatus = (data) => {
	if (data.ingestionStatus == 'INGESTED') {
		return 'success';
	} else if (data.ingestionStatus == 'LOADED' || data.ingestionStatus == 'ERROR') {
		return 'danger';
	} else if (data.ingestionStatus == 'IN PROGRESS' || data.ingestionStatus == 'INGESTION_QUEUE' || data.ingestionStatus == 'INGESTING') {
		return 'info';
	} else {
		return 'warning';
	}
}


const updateFilterModel = () => {
	console.log("updateFilterModel")
}

// Funzione per scaricare il file
const downloadFile = async (video) => {
	console.log("video", video)

	try {

		const response = await KsVideoService.downloadKsVideo(video);
		console.log("response download", response);

		const contentType = response.headers['content-type']; // Tipo MIME dinamico
		const blob = new Blob([response.data], { type: contentType });

		// Crea un URL temporaneo per il download
		const url = window.URL.createObjectURL(blob);
		const link = document.createElement('a');
		link.href = url;

		const fileName = video.fileName;
		console.log("fileName", fileName)

		link.setAttribute('download', fileName);
		document.body.appendChild(link);
		link.click();
		link.remove();

	} catch (error) {
		console.error("Error while downloading the file:", error);
		toast.add({ severity: 'error', summary: 'Error', detail: 'Error while downloading the file. Check the file name.', life: 3000 });
	}
};

const editKsVideo = (data) => {
	console.log(data);
	router.push({ name: 'ks-video-edit', params: { id: data.id } });
}

const openSimilaritySearch = (video) => {
	ksVideoStore.setSelectedKsVideo(video).then(() => {
		router.push({ name: 'ks_similarity_search' });
	});
}

const confirmDeleteFromVectorStore = (id) => {
	console.log("OK");
	confirm.require({
		target: event.target,
		message: 'Are you sure you want to proceed?',
		icon: 'pi pi-exclamation-triangle',
		rejectProps: {
			label: 'Cancel',
			class: "p-button",
			outlined: true,
		},
		acceptProps: {
			label: 'Delete',
			severity: 'danger',
		},
		accept: () => {
			const videoToDelete = ksVideos.value.find(video => video.id === id);
			if (!videoToDelete) {
				console.error('Video not found');
				return;
			}

			const requestPayload = {
				ksDocumentId: 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/deleteVideoRecordsFromVectorStore', requestPayload)
				.then(response => {
					console.log('Delete resource:', response.data)
					ksVideos.value.forEach(element => {
						if (element.id == id) {
							element.ingestionStatus = "DELETING"
							console.log("Updated element", element)
						}
					});
					toast.add({ severity: 'success', summary: 'Success', detail: 'Deletion Completed', life: 3000 });
				})
				.catch(error => {
					console.error('Error deleting records: ', error)
					toast.add({ severity: 'error', summary: 'Error', detail: 'Error in Deletion', life: 3000 });
				});
		}
	})
};

// Funzione per cancellare record in stato LOADED
const deleteLoadedRecord = async (id) => {
		confirm.require({
		target: event.target,
		message: 'Are you sure you want to proceed?',
		icon: 'pi pi-exclamation-triangle',
		rejectProps: {
			label: 'Cancel',
			class: "p-button",
			outlined: true,
		},
		acceptProps: {
			label: 'Delete',
			severity: 'danger',
		},
		accept: async () => {
			toast.add({ severity: 'info', summary: 'Info', detail: 'Deleting record...', life: 3000 });
			const videoToDelete = ksVideos.value.find(video => video.id === id);
			if (!videoToDelete) {
				toast.add({ severity: 'error', summary: 'Error', detail: 'Video not found', life: 3000 });
				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,
			};
			try {
				await ksVideoStore.deleteKsVideoRecord(requestPayload);
				toast.add({ severity: 'success', summary: 'Success', detail: 'Record deleted', life: 3000 });
				updateVideos();
			} catch (error) {
				toast.add({ severity: 'error', summary: 'Error', detail: 'Error deleting record', life: 3000 });
			}
		}
	})
};


//ingestion
const startIndividualngestion = (id) => {
	toast.add({ severity: 'info', summary: 'Info', detail: 'Starting indexing...', life: 3000 });
	fe_status.value = "INGESTION_QUEUE"
	axios.get(`/test/index_video/${id}`)
		.then(response => {
			if (response.data.status == "OK") {
				toast.add({ severity: 'success', summary: 'Success', detail: 'Video indexing started...', life: 3000 });
				fe_status.value = "INGESTION_QUEUE"
			}
			if (response.data.status == "ERROR") {
				toast.add({ severity: 'error', summary: 'Success', detail: 'Error indexing video:' + response.data.message, life: 3000 });
				fe_status.value = "ERROR"
			}
			ksVideos.value.forEach(element => {
				if (element.id == id) {
					element.ingestionStatus = fe_status.value
					console.log("Updated element", element)
				}
			});
		})
		.catch(error => {
			//ingestionDialogVisible.value = true;
			console.error('Error indexing record: ', error)
			toast.add({ severity: 'error', summary: 'Success', detail: 'Error ingesting video:' + error, life: 3000 });
		});
};


//new record creation
const newKsVideo = () => {
	router.push({ name: 'ks-video-new' });
};

const getFileIcon = (filename) => {
	const ext = filename.split('.').pop();
	if (ext === 'pdf') {
		return 'pi pi-file-pdf';
	} else if (ext === 'doc' || ext === 'docx') {
		return 'pi pi-file-word';
	} else if (ext === 'xls' || ext === 'xlsx') {
		return 'pi pi-file-excel';
	} else if (ext === 'ppt' || ext === 'pptx') {
		return 'pi pi-file-powerpoint';
	} else if (ext === 'mp4') {
		return 'pi pi-video';
	} else {
		return 'pi pi-file';
	}
}

const mapDocType = (type) => {
	const mapping = {
		'functional_video': 'Functional video',
		'code_instruction_video': 'Code Instruction video',
		'specification_video': 'Specification video',
		'other_video': 'Other'
	};
	return mapping[type] || type;
};

function formatDate(dateString) {
	return moment(dateString).format('DD/MM/YYYY');
}

</script>

<style scoped>
/* Custom styling for disabled red button */
.p-button-danger {
	background-color: white;
	border-color: blue;
	color: black;
}

.p-button-danger:disabled {
	/*background-color: red;*/
	border-color: red;
	color: red;
	cursor: not-allowed;
}

.spinner-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	animation: fade-in 1s ease-in-out;
}

.spinner {
	animation: spin 1s linear infinite;
	width: 50px;
	height: 50px;
	color: var(--primary-color, #007bff);
}


@keyframes spin {
	0% {
		transform: rotate(0deg);
	}

	100% {
		transform: rotate(360deg);
	}
}

@keyframes pulse {

	0%,
	100% {
		opacity: 1;
		color: var(--primary-color, #007bff);
	}

	50% {
		opacity: 0.11;
		color: var(--primary-color, #007bff);
	}
}

@keyframes fade-in {
	from {
		opacity: 0;
	}

	to {
		opacity: 1;
	}
}

.card {
	margin: 2rem;
}
</style>