<template>
	<div class="card">
		<Toast />
		<ConfirmPopup></ConfirmPopup>
		<div v-if="loading" class="loading-container">
			<div class="spinner-container">
				<ProgressSpinner class="spinner" />
				<p class="loading-text">Loading data...</p>
			</div>
		</div>

		<DataTable v-model:filters="filters" :value="ksdocuments" paginator showGridlines :rows="10" dataKey="id"
			filterDisplay="menu" :loading="loading"
			:globalFilterFields="['ingestionInfo.metadata.KsApplicationName', 'ingestionInfo.metadata.KsFileSources', 'ingestionInfo.metadata.KsDocSource', 'ingestionStatus', 'ingestionDateFormat']">
			<template #header>
				<div class="flex items-center justify-between gap-4 p-4 ">
					<span class="text-xl font-bold">Knowledge Source Documents</span>
					<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="Keyword Search" />
						</IconField>
					</div>
					<Button icon="pi pi-plus" rounded raised @click="newKsDocument()" v-tooltip="'Create New Document'"
						class="mr-2" />
					<Button icon="pi pi-check-circle" rounded raised @click="startlngestion()"
						v-tooltip="'Start All documents Ingestion'" class="mr-8" :disabled="allDocumentsIngested"
						:class="{ 'p-button-danger': allDocumentsIngested }" />
				</div>
			</template>
			<template #empty>No Records found</template>

			<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.KsProjectName" header="KsProjectName" sortable
				style="min-width: 12rem">
				<template #body="{ data }">
					{{ data.ingestionInfo.metadata.KsProjectName }}
				</template>
			</Column>
			<Column field="ingestionInfo.metadata.KsFileSource" header="FileSource" sortable>
				<template #body="{ data }">
					{{ data.ingestionInfo.metadata.KsFileSource }}
				</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.KsDocSource" header="DocSource" sortable style="min-width: 12rem">
				<template #body="{ data }">
					{{ data.ingestionInfo.metadata.KsDocSource }}
				</template>
				<template #filter="{ filterModel, filterCallback }">
					<InputText v-model="filterModel.value" type="text" @input="filterCallback()"
						placeholder="Search by File" />
				</template>
			</Column>
			<Column field="ingestionStatus" header="Status" sortable>
				<template #body="slotProps">
					<Tag :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 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 headerStyle="width: 5rem; text-align: center" bodyStyle="text-align: center; overflow: visible">
				<template #body="slotProps">
					<div class="flex justify-center items-center space-x-3">
						<!--Button type="button" icon="pi pi-pencil" rounded @click="editKsDocument(slotProps.data)"
							v-tooltip="'Edit the information of document'" /-->
						<Button type="button" icon="pi pi-play" rounded
							@click="startIndividualngestion(slotProps.data.id)"
							v-tooltip="'Start Ingestion of document'"
							:disabled="slotProps.data.ingestionStatus === 'INGESTED'"
							:class="{ 'p-button-danger': slotProps.data.ingestionStatus === 'INGESTED' }" />
						<Button type="button" icon="pi pi-trash" rounded @click="confirmDelete(slotProps.data.id)"
							v-tooltip="'Delete the ingested Record'"
							:disabled="slotProps.data.ingestionStatus === 'NEW'"
							:class="{ 'p-button-danger': slotProps.data.ingestionStatus === 'NEW' }" />
					</div>
				</template>
			</Column>
		</DataTable>
		<Dialog header="Ingestion Result" v-model:visible="ingestionDialogVisible" :modal="true" :closable="false">
			<p>{{ ingestionResult }}</p>
			<Button label="OK" icon="pi pi-check" @click="ingestionDialogVisible = false" />
		</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 { computed, onMounted, ref } from 'vue';
import { 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 ProgressSpinner from 'primevue/progressspinner';
import Select from 'primevue/select';
import Tag from 'primevue/tag';


const router = useRouter()
const ksdocuments = ref(null);
const loading = ref(true);
const toast = useToast();
const confirm = useConfirm();

const ingestionDialogVisible = ref(false);
const ingestionResult = ref('');
const filters = ref();

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', 'INGESTED', 'FAILED']); // Add your statuses here

onMounted(() => {
	axios.get('/fe-api/ksdocuments')
		.then(response => {
			ksdocuments.value = getCustomDatewithAllResponse(response.data);
			console.log(ksdocuments.value);
			loading.value = false;
		});
});

// Computed property to check if all documents are ingested
const allDocumentsIngested = computed(() => {
	return ksdocuments.value && ksdocuments.value.every(doc => doc.ingestionStatus === 'INGESTED');
});


const getStatus = (data) => {
	if (data.ingestionStatus === 'INGESTED') {
		return 'success';
	} else if (data.ingestionStatus === 'NEW') {
		return 'danger';
	} else {
		return 'warn';
	}
}

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

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

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

const confirmDelete = (id) => {
	console.log("id", id);

	confirm.require({
		target: event.currentTarget,
		message: 'Are you sure you want to proceed?',
		icon: 'pi pi-exclamation-triangle',
		rejectProps: {
			label: 'Cancel',
			severity: 'secondary',
			outlined: true
		},
		acceptProps: {
			label: 'Delete',
			severity: 'danger',
		},
		accept: () => {
			const documentToDelete = ksdocuments.value.find(doc => doc.id === id);
			console.log("documentToDelete", documentToDelete)
			if (!documentToDelete) {
				console.error('Document not found');
				return;
			}

			const requestPayload = {
				ksDocumentId: id,
				ksIngestionInfoId: documentToDelete.ingestionInfo.id,
				ksDoctype: documentToDelete.ingestionInfo.metadata.KsDoctype,
				ksDocSource: documentToDelete.ingestionInfo.metadata.KsDocSource,
				ksFileSource: documentToDelete.ingestionInfo.metadata.KsFileSource,
				ksApplicationName: documentToDelete.ingestionInfo.metadata.KsApplicationName,
			};
			console.log("requestPayload", requestPayload)

			axios.post('/fe-api/vector-store/deleteRecords', requestPayload)
				.then(response => {
					console.log('Delete resource:', response.data)
					ksdocuments.value = ksdocuments.value.filter(doc => doc.id !== id);
					console.log('ksdocuments.value', ksdocuments.value)
					toast.add({ severity: 'info', summary: 'Confirmed', detail: 'deletion is in PROGRESS', life: 3000 });
				})
				.catch(error => {
					console.error('Error deleting records: ', error)
					toast.add({ severity: 'error', summary: 'Error', detail: 'Error in Deletion', life: 3000 });
				});
		},
		reject: () => {
			toast.add({ severity: 'error', summary: 'Rejected', detail: 'You have rejected', life: 3000 })
		}
	})
};

//ingestion
const startIndividualngestion = (id) => {
	axios.get(`/test/ingest_document/${id}`)
		.then(response => {
			ingestionResult.value = response.data;
			if (response.data.status == "OK") {
				ksdocuments.value.forEach(element => {
					if (response.data.ingestedDocumentId.includes(element.id)) {
						element.status = "INGESTED"
					}
				});
			} else {
				ingestionResult.value = `Error: ${response.data.message}`;
			}

			ingestionDialogVisible.value = true;
		})
		.catch(error => {
			ingestionDialogVisible.value = true;
		});
};

const startlngestion = () => {
	axios.get('/test/ingestion_loop')
		.then(response => {
			ingestionResult.value = response.data;
			if (response.data.status == "OK") {
				ksdocuments.value.forEach(element => {
					if (response.data.ingestedDocumentId.includes(element.id)) {
						element.status = "INGESTED"
					}
				});
			} else {
				ingestionResult.value = `Error: ${response.data.message}`;
			}

			ingestionDialogVisible.value = true;
		})
		.catch(error => {
			ingestionDialogVisible.value = true;
		});
};

//new record creation
const newKsDocument = () => {
	console.log('new');
	router.push({ name: 'ks-document-new' });

}

// Function to format date string
function formatDate(dateString) {
	// Parse the date string using moment
	return moment(dateString).format('MM/DD/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;
}

.space-x-3>*+* {
	margin-left: 1rem;
	/* Adjust as needed for desired spacing */
}

.loading-container {
	display: flex;
	align-items: center;
	justify-content: center;
	position: fixed;
	/* Change to fixed */
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 9999;
	/* Ensure it’s on top of everything */
	background-color: rgba(255, 255, 255, 0.8);
	/* Optional: Add a background to obscure content */
}

.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);
}

.loading-text {
	font-size: 1.2rem;
	animation: pulse 1.5s infinite;
	margin-top: 10px;
	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>