<template>
    <div>
        <div class="content-section introduction big-title">
            <div class="feature-intro">
                <h1>Repository <span>DataTable</span></h1>
            </div>
        </div>

        <div class="card">
            <Toast />
            <ConfirmPopup></ConfirmPopup>
            <Toolbar class="mb-6">
                <template #start>
                    <Button label="Refresh" icon="pi pi-refresh" severity="secondary" class="mr-2" rounded
                        @click="refreshPage" v-tooltip.top="'Refresh all records'" />
                </template>

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

                    <Dialog v-model:visible="showDialog" :style="{ width: '50rem' }" header="Repository Details"
                        :modal="true">
                        <div>
                            <cloneForm @submitForm="cloneRepo" @cancel="showDialog = false" />
                        </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" sortMode="single" sortField="ksGitIngestionInfo.metadata.KsApplicationName"
                :sortOrder="1" filterDisplay="menu" :loading="loading"
                :globalFilterFields="['branch', 'cloneStatus', '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>
                    <div class=" flex justify-content-center">
                        <ProgressSpinner />
                    </div>
                </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="cloneStatus" header="Clone Status" sortable>
                    <template #body="slotProps">
                        <Tag :value="slotProps.data.cloneStatus" :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({ cloneStatus: option })" />
                            </template>
                        </Select>
                    </template>
                </Column>

                <Column field="ingestionStatus" header="ingestion 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.top="'Start Ingestion of Git'"
                            :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.top="'Ingest Latest changes From Git'" />

                        <Button text raised rounded severity="danger" type="button" icon="pi pi-trash"
                            @click="deleteRecordsFromVectorStore(slotProps.data)" v-tooltip.top="'Delete 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>
    </div>
</template>

<script setup>
import logo from '@/assets/gitlab-logo.svg';
import VueJsonView from '@matpool/vue-json-view';
import { FilterMatchMode, FilterOperator } from '@primevue/core/api';
import axios from 'axios';
import moment from 'moment';
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 Select from 'primevue/select';
import Tag from 'primevue/tag';
import { useConfirm } from "primevue/useconfirm";

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

import ProgressSpinner from 'primevue/progressspinner';


//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 statuses = ref(['ERROR', 'IN-PROGRESS', 'INGESTED', 'NEW', 'COMPLETED']);

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

const logoSrc = ref(logo);

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

const refreshPage = () => {
    location.reload(); // Reloads the current page
};


//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 filters = ref({
    global: { value: null, matchMode: FilterMatchMode.CONTAINS },
    id: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.EQUALS }] },
    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 }] },
    cloneStatus: { 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;
}

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 === 'IN-PROGRESS' || data.cloneStatus === 'IN-PROGRESS') {
        return 'info';
    } else if (data.ingestionStatus === 'ERROR' || data.cloneStatus === 'IN-PROGRESS') {
        return 'danger';
    } else if (data.ingestionStatus === 'NEW' || data.cloneStatus === 'NEW') {
        return 'warning';
    } else if (data.ingestionStatus === 'COMPLETED' || data.cloneStatus === 'COMPLETED') {
        return 'contrast';
    } else {
        return 'secondary';
    }
};

//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.cloneStatus !== '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 */
}

.big-title {
    font-size: 3rem;
    color: #c1c3c4;
    /* Adjust the size as needed */
    font-weight: bold;
    margin-bottom: 1rem;
    margin-left: 2rem;
}

.big-title span {
    color: #c1c3c4;

    font-size: 2rem;
    /* Optional: style the span element differently */
}
</style>