<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>
        <Toolbar class="mb-6">
                <template #start>
                    <Button label="Refresh" icon="pi pi-refresh" severity="secondary" class="mr-2" rounded  @click="fetchCodeRepoInfo" />
                </template>

                <template #end>
                    <Button label="Expand All" icon="pi pi-plus" severity="secondary" class="mr-3" rounded   @click="expandAll" />
                    <Button label="Collapse All"  icon="pi pi-minus" severity="secondary" class="mr-3" rounded  @click="collapseAll"/>
                    <!--Button label="Add New Git Repo" icon="pi pi-plus"  severity="secondary" rounded class="mr-3" @click="newCodeRepoForm()" v-tooltip="'Add New Git Repo'" class="mr-2" /-->
                    <!--Button label="Add Git Repo" icon="pi pi-bolt"  severity="secondary" rounded  @click="cloneRepoForm()" v-tooltip="'Add New Git Repo'" /-->
                    <Button label="Add Git Repo" icon="pi pi-bolt"  severity="secondary" rounded  @click="showDialog = true" v-tooltip="'Add New Git Repo using Dialog'"/>

                    <Dialog v-model:visible="showDialog" :style="{ width: '600px' }" header="Repository Details" :modal="true">
                        <div>
                            <cloneForm @submitForm="cloneRepo"/>
                        </div>
                    </Dialog>
                </template>
        </Toolbar>

        <DataTable
            v-model:filters="filters"
            v-model:expandedRows="expandedRows"
            @rowExpand="onRowExpand"
            @rowCollapse="onRowCollapse"
            :value="codeRepoInfo"
            :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"
            groupRowsBy="repoName"
            filterDisplay="menu"
            :loading="loading"
            :globalFilterFields="['repoName', 'branch', 'ingestionStatus', 'ingestionDateFormat']"
            tableStyle="min-width: 70rem"
            removableSort
            
        >
        <template #header>
                <div class="flex flex-wrap gap-2 items-center justify-between">
                    <h4 class="m-0">Manage Repositories</h4>
                    <IconField>
                        <InputIcon>
                            <i class="pi pi-search" />
                        </InputIcon>
                        <InputText v-model="filters['global'].value" placeholder="Search..." />
                    </IconField>
                </div>
        </template>
            <template #groupheader="slotProps">
                <div class="flex items-center gap-2">
                    <img :alt="slotProps.data.repoName" :src="logoSrc" width="32" style="vertical-align: middle" />
                    <span>{{ slotProps.data.repoName }}</span>
                </div>
            </template>

            <Column expander style="width: 5rem" />

            <template #empty>No Records found</template>
            <template #loading>Loading Data... </template>
            <socketManager @update="handleCloneRepoWebSocketMessage" topic="topic" subtopic="clone-status"></socketManager>
            <socketManager @update="handleCloneRepoWebSocketMessage" topic="topic" subtopic="deletion-status"></socketManager>

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

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

            <Column field="repoName" header="Repo Name">
                <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">
                <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"-->
            <Column :exportable="false" style="min-width: 12rem">
                <template #body="slotProps">
                    
                        <Button 
                            text raised rounded
                            severity="info"
                            type="button" 
                            class="mr-2"
                            icon="pi pi-play"
                            @click="ingestGitRepo(slotProps.data)"
                            v-tooltip="'Start Ingestion of Repo'"
                            :disabled="isButtonDisabled(slotProps.data)"
                        />

                        <Button 
                            text raised rounded
                            severity="warn"
                            type="button"
                            class="mr-2" 
                            icon="pi pi-forward"
                            @click="reIngestWithPullChanges(slotProps.data)" 
                            v-tooltip="'Ingest Repo with latest changes from master branch'"
                        />

                        <Button 
                            text raised rounded
                            severity="danger"
                            type="button" 
                            icon="pi pi-trash"
                            @click="deleteRecordsFromVectorStore(slotProps.data)" 
                            v-tooltip="'Delete the Records'"
                        />
                    
                </template>
            </Column>
            

            <template #expansion="slotProps">
                <div class="p-4">
                    <VueJsonView :src="slotProps.data" 
                                 :collapsed="collapsed"
                                 :theme="theme"
                                 :sort-keys="sortKeys"
                                 :enable-clipboard="enableClipboard"
                                 class="vue-json-view"
                    />
                </div>
            </template>

            <template #groupfooter="slotProps">
                <div class="flex justify-end font-bold w-full">Total Count: {{ calculateCustomerTotal(slotProps.data.repoName) }}</div>
            </template>
        </DataTable>
    </div>
</template>

<script setup>
import { FilterMatchMode, FilterOperator } from '@primevue/core/api';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useToast } from 'primevue/usetoast';
import axios from 'axios';
import moment from 'moment';
import {setWebSocketMessageHandler} from '/src/service/websocketService.js';
import VueJsonView from '@matpool/vue-json-view'
import logo from '@/assets/gitlab-logo.svg';

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";

import socketManager from '/src/components/SocketManager.vue'

//dialog
import cloneForm from './KsGitCloneRepoFormDialog.vue'
const showDialog = ref(false);
const cloneRepo = (formData) => {
    try {
        const response = axios.post('/fe-api/ks_git_repos/clone', formData, {
            headers: {
                'Content-Type': 'application/json'
            }
        });
        
        console.log('Submit successful:', response.data);
        toast.add({ severity: 'success', summary: 'Success', detail: 'Repository Download is IN-PROGRESS', life: 3000 });
    } catch (error) {
        console.error('Submit failed:', error);
        toast.add({ severity: 'error', summary: 'Error', detail: 'Repository Submission failed', life: 3000 });
    }
    showDialog.value = false; // Close the dialog after form submission
};

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

const ingestionResult = ref('');
const popupTitle = ref('');
const popupMessage = ref('');
const filters = ref();
const statuses = ref(['INGESTION-ERROR','INGESTION-IN-PROGRESS', 'INGESTED', 'REPO-NEW', 'REPO-CLONE-IN-PROGRESS','REPO-CLONE-COMPLETED','REPO-CLONE-FAILED']);

const collapsed = ref(1)
const theme = ref('bright:inverted')
const sortKeys = ref(true)
const enableClipboard = ref(true)

const logoSrc = ref(logo);

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


//websocket
const handleCloneRepoWebSocketMessage = (data) => {
    console.log('Update received in parent component:', data);
  const { success, message } = data;
  if (success) {
    toast.add({ severity: 'success', summary: 'Success', detail: message , life: 10000 });
    fetchCodeRepoInfo();
  } else {
    toast.add({ severity: 'error', summary: 'Error', detail: message, life: 10000 });
    fetchCodeRepoInfo();
  }
};
//websocket end

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 }] }
    };
};



function calculateCustomerTotal(name) {
    let total = 0;
    if(codeRepoInfo.value){
        for(let RepoInfo of codeRepoInfo.value){
            if (RepoInfo.repoName === name) {
                total++;
            }
        }
    }
    return total;
}

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


//ingest git repo functions
const ingestGitRepo = (repo) => {    
    confirm.require({
        target: event.currentTarget,
        message: 'Are you sure you want to proceed?',
        icon: 'pi pi-exclamation-circle',
        rejectProps: {
            label: 'Cancel',
            severity: 'secondary',
            outlined: true
        },
        acceptProps: {
            label: 'Ingest Record',
            severity: 'danger',
        },
        accept: () => {
            axios.get(`/test/ingest_repo?repoName=${repo.repoName}&branchName=${repo.branch}`)
            .then((response) => {
                toast.add({ severity: 'success', summary: 'Ingestion Summary', detail: 'Repository Ingestion Started', life: 6000 });
                console.log('Delete resource:', response.data)
            })
            .catch((error) => {
                console.error('Error deleting records: ', error)
                toast.add({ severity: 'error', summary: 'Error', detail: 'Error Ingesting records:', life: 6000 });
            });
        },
        reject: () => {
            toast.add({severity: 'error', summary: 'Rejected', detail: 'You have rejected', life: 3000})
        }
    })
};

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

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
const deleteRecordsFromVectorStore = (data) =>{
    console.log("data",data);
    console.log("reponame",data.repoName);

    const requestPayload = {
		ksGitInfoId: data.id,
		ksGitIngestionInfoId: data.ksGitIngestionInfo.id,
		ksDoctype: data.ksGitIngestionInfo.metadata.KsDoctype,
		ksDocSource: data.ksGitIngestionInfo.metadata.KsDocSource,
		ksFileSource: data.ksGitIngestionInfo.metadata.KsFileSource,
		ksApplicationName: data.ksGitIngestionInfo.metadata.KsApplicationName,
        ksBranch: data.ksGitIngestionInfo.metadata.KsBranch
	};
    console.log("requestPayload",requestPayload)

    confirm.require({
        target: event.currentTarget,
        message: 'Are you sure you want to proceed?',
        icon: 'pi pi-exclamation-circle',
        rejectProps: {
            label: 'Cancel',
            severity: 'secondary',
            outlined: true
        },
        acceptProps: {
            label: 'Delete Records',
            severity: 'danger',
        },
        accept: () => {
            axios.post('/fe-api/vector-store/deleteGitRecords', requestPayload)
            .then(response => {
                toast.add({ severity: 'info', summary: 'Deletion', detail: 'Records Deletion INPROGRESS', life: 6000 });
                console.log('Delete resource:', response.data)
            })
            .catch(error => {
                console.error('Error deleting records: ', error)
                toast.add({ severity: 'error', summary: 'Error', detail: 'Error deleting records:', life: 6000 });
            });
        },
        reject: () => {
            toast.add({severity: 'error', summary: 'Rejected', detail: 'You have rejected', life: 3000})
        }
    })
};

//reingest latest changes
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-circle',
        rejectProps: {
            label: 'Cancel',
            severity: 'secondary',
            outlined: true
        },
        acceptProps: {
            label: 'Reingest Latest Changes',
            severity: 'danger',
        },
        accept: () => {
           axios.get(`/test/reingest_repo?repoName=${data.repoName}&branchName=${data.branch}`)
           .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})
        }
    })
};

//expand
const onRowExpand = (event) => {
    console.log('Row Expanded:', event.data);
    toast.add({ severity: 'info', summary: event.data.repoName +' Expanded', life: 3000 });
};
const onRowCollapse = (event) => {
    console.log('Row Expanded:', event.data);
    toast.add({ severity: 'success', summary: event.data.repoName +' Collapsed', life: 3000 });
};

const expandAll = () => {
    expandedRows.value = codeRepoInfo.value.reduce((acc, item) => {
        (acc[item.id] = true);
        return acc;
    }, {});
};
const collapseAll = () => {
    expandedRows.value = {};
};

//disable button

function isButtonDisabled(data) {
    return data.ingestionStatus !== 'REPO-CLONE-COMPLETED';
}
</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;
}
.vue-json-view {
    font-size: 15px; /* Change this value to your desired font size */
}

</style>