<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-else
            v-model:filters="filters"
            :value="codeRepoInfo"
            :paginator="true"
            :rows="10"
            dataKey="repoName"
            :rowHover="true"
            showGridlines
            filterDisplay="menu"
            :loading="loading"
            :globalFilterFields="['repoName', 'branch', 'ingestionStatus', 'ingestionDateFormat']"
        >
            <template #header>
                <div class="flex items-center justify-between gap-4 p-4">
                    <span class="text-xl font-bold">Code Repository</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="newCodeRepoForm()" v-tooltip="'Add New Git Repo'" class="mr-2" />
                    <Button icon="pi pi-bolt" rounded raised @click="cloneRepoForm()" v-tooltip="'Clone New Git Repo'" class="mr-2" />
                </div>
            </template>

            <template #empty>No Records found</template>
            <template #loading>Loading Data... </template>

            <!--Column field="id" header="KSGitInfoID" sortable /-->

            <!--Column field="ksGitIngestionInfo.id" header="ksGitIngestionInfo" sortable> </Column-->

            <Column field="repoName" header="Repo Name" sortable>
                <template #body="{ data }">
                    {{ data.repoName }}
                </template>
                <template #filter="{ filterModel, filterCallback }">
                    <InputText v-model="filterModel.value" type="text" @input="filterCallback()" placeholder="Search by Git Repo Name" />
                </template>
            </Column>

            <Column field="branch" header="Branch" sortable>
                <template #body="{ data }">
                    {{ data.branch }}
                </template>
                <template #filter="{ filterModel, filterCallback }">
                    <InputText v-model="filterModel.value" type="text" @input="filterCallback()" placeholder="Search by Git Repo Branch" />
                </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 field="ingestionDate" header="Ingestion Date" sortable 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 header="Actions" 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-play"
                        class="p-button-rounded p-button-success p-mr-2"
                        @click="ingestGitRepo(slotProps.data)"
                        v-tooltip="'Start Ingestion of Repo'"
                        :disabled="slotProps.data.ingestionStatus === 'INGESTED'"
                        :class="{ 'p-button-danger': slotProps.data.ingestionStatus === 'INGESTED' }"
                    />
                
                <Button type="button" icon="pi pi-forward" severity="danger" rounded @click="reIngestWithPullChanges(slotProps.data)" v-tooltip="'Ingest Repo with latest changes from master branch'"/>
                
                <Button type="button" icon="pi pi-trash" rounded @click="showConfirmDialog(slotProps.data.id)"
							v-tooltip="'Delete the Records'"  />
                
                
                </div>

                <Dialog header="Confirm Deletion" :visible="confirmDialogVisible" modal @hide="resetConfirmDialog"
							:style="{ width: '300px' }">
							<p>Are you sure you want to delete this record?</p>
							<template #footer>
								<Button label="No" icon="pi pi-times" @click="confirmDialogVisible = false"/>
								<Button label="Yes" icon="pi pi-check" @click="confirmDelete" class="p-button-danger" />
							</template>
				</Dialog>
                </template>
            </Column>
        </DataTable>
        <Dialog v-model:visible="ingestionDialogVisible" :header="popupTitle">
            <p>{{ popupMessage }}</p>
            <Button label="OK" icon="pi pi-check" @click="ingestionDialogVisible = false" />
        </Dialog>
    </div>
</template>

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

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 Tooltip from 'primevue/tooltip';
import ProgressSpinner from 'primevue/progressspinner';
import { useConfirm } from "primevue/useconfirm";

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

const confirmDialogVisible = ref(false);
const recordToDelete = ref(null);

const ingestionDialogVisible = ref(false);
const ingestionResult = ref('');
const popupTitle = ref('');
const popupMessage = ref('');
let checkStatusInterval = null;
const filters = ref();
const statuses = ref(['NEW', 'INGESTED', 'FAILED', 'INPROGRESS']);

onMounted(() => {
    fetchCodeRepoInfo();
});

const initFilters = () => {
    filters.value = {
        global: { value: null, matchMode: FilterMatchMode.CONTAINS },
        id: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.EQUALS }] },
        repoName: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.STARTS_WITH }] },
        branch: { 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 fetchCodeRepoInfo = async () => {
    try {
        const response = await axios.get('/fe-api/ks_git_repos');
        //codeRepoInfo.value = response.data;
        codeRepoInfo.value = getCustomDatewithAllResponse(response.data);
        console.log(codeRepoInfo.value);
        loading.value = false;
    } catch (error) {
        console.error('Failed to fetch code repo info:', error);
    }
};

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

//-------------------------------------------------------------------------------------------------------

const ingestGitRepo = (repo) => {
    axios
        .get(`/test/ingest_repo/${repo.repoName}`)
        .then((response) => {
            showPopup('Ingestion started', 'info');
            toast.add({ severity: 'success', summary: 'Ingestion Summary', detail: 'Repository Ingestion Started', life: 3000 });
            startPollingStatus(repo.repoName);
        })
        .catch((error) => {
            showPopup('Error starting ingestion', 'error');
        });
};

const startPollingStatus = (repoName) => {
    if (checkStatusInterval) {
        // Prevent starting multiple intervals if there's already one running
        clearInterval(checkStatusInterval);
    }

    checkStatusInterval = setInterval(() => {
        checkIngestionStatus(repoName);
    }, 100000); // Poll every 1 minute
};

const checkIngestionStatus = (repoName) => {
    axios
        .get(`/test/check_ingestion_status/${repoName}`)
        .then((response) => {
            const data = response.data;
            if (data.status === 'INGESTED') {
                clearInterval(checkStatusInterval);
                checkStatusInterval = null; // Reset interval reference
                showPopup('Ingestion completed successfully', 'success');
                updateRepositoryStatus(data.ingestedDocumentId);
            } else if (data.status === 'ERROR') {
                clearInterval(checkStatusInterval);
                checkStatusInterval = null; // Reset interval reference
                showPopup(`Error: ${data.message}`, 'error');
            }
        })
        .catch((error) => {
            clearInterval(checkStatusInterval);
            checkStatusInterval = null; // Reset interval reference
            showPopup('Error checking ingestion status', 'error');
        });
};

const updateRepositoryStatus = (ingestedDocumentId) => {
    // Update status of the repository in your local state or data
    codeRepoInfo.value.forEach((element) => {
        if (ingestedDocumentId.includes(element.id)) {
            element.status = 'INGESTED';
        }
    });
};

const showPopup = (message, severity) => {
    popupMessage.value = message;
    popupTitle.value = severity === 'success' ? 'Success' : severity === 'error' ? 'Error' : severity === 'info' ? 'Ingestion Status' : 'Notification';
    ingestionDialogVisible.value = true;
};

// ---------------------------------------------------------------------------------------------------------

const allDocumentsIngested = computed(() => {
    return codeRepoInfo.value && codeRepoInfo.value.every((doc) => doc.ingestionStatus === 'INGESTED');
});

const updateFilterModel = () => {
    console.log('updateFilterModel');
};

const newCodeRepoForm = () => {
    console.log('new');
    router.push({ name: 'ks-git-repo-new' });
};

const cloneRepoForm = () =>{
    console.log("clone repo form");
    router.push({ name: 'ks-git-clone-repo' });
}

function formatDate(dateString) {
    // Parse the date string using moment
    return moment(dateString).format('MM/DD/YYYY');
}

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

//delete functionality
function showConfirmDialog(id) {
	recordToDelete.value = id;
	confirmDialogVisible.value = true;
}

function confirmDelete() {
	if (recordToDelete.value !== null) {
		deleteRecordsFromVectorStore(recordToDelete.value);
		recordToDelete.value = null;
	}
	confirmDialogVisible.value = false;
}

function resetConfirmDialog() {
	recordToDelete.value = null;
}


const deleteRecordsFromVectorStore = (id) => {
	const ksGitInfoToDelete = codeRepoInfo.value.find(ksGitInfo => ksGitInfo.id === id);

	if (!ksGitInfoToDelete) {
		console.error('Repository not found');
		return;
	}

	const requestPayload = {
		ksGitInfoId: id,
		ksGitIngestionInfoId: ksGitInfoToDelete.ksGitIngestionInfo.id,
		ksDoctype: ksGitInfoToDelete.ksGitIngestionInfo.metadata.KsDoctype,
		ksDocSource: ksGitInfoToDelete.ksGitIngestionInfo.metadata.KsDocSource,
		ksFileSource: ksGitInfoToDelete.ksGitIngestionInfo.metadata.KsFileSource,
		ksApplicationName: ksGitInfoToDelete.ksGitIngestionInfo.metadata.KsApplicationName
	};

	axios.post('/fe-api/vector-store/deleteGitRecords', requestPayload)
		.then(response => {
			console.log('Delete resource:', response.data)
			codeRepoInfo.value = codeRepoInfo.value.filter(ksGitInfo => ksGitInfo.id !== id);
		})
		.catch(error => {
			console.error('Error deleting records: ', error)
		});
}

const reIngestWithPullChanges = (data) =>{
    console.log("data",data);
    console.log("reponame",data.repoName);

    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: 'Ingest Changes',
            severity: 'danger',
        },
        accept: () => {
           axios.get('/test/reingest_repo/'+data.repoName)
           .then(response => {
            console.log(response.data);
            toast.add({ severity: 'info', summary: 'Confirmed', detail: 'ReIngestion with latest pull from master started', life: 3000 });
           }).catch(error => {
            console.log(error);
            toast.add({ severity: 'error', summary: 'Error', detail: 'Error in Reingestion', life: 3000 });
           })
        },
        reject: () => {
            toast.add({severity: 'error', summary: 'Rejected', detail: 'You have rejected', life: 3000})
        }
    })
};
</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;
    height: 100%; /* Ensure the container takes full height of the parent */
    min-height: 400px; /* Adjust this height to your DataTable height */
}

.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>
