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

const textInfo = ref(null);
const toast = useToast();
const confirm = useConfirm();

const filters = ref({
    global: { value: null, matchMode: FilterMatchMode.CONTAINS },
    name: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.CONTAINS }] },
    ingestionDateFormat: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.DATE_IS }] },
    ingestionStatus: { operator: FilterOperator.OR, constraints: [{ value: null, matchMode: FilterMatchMode.EQUALS }] }
});
onMounted(() => {
    fectchDetails();
});

const fectchDetails = async () => {
    try {
        const response = await axios.get('/texts');
        console.log(response.data);
        textInfo.value = getCustomDatewithAllResponse(response.data);
    } catch (error) {
        console.error('Failed to fetch texts info: ', error)
    }
}

const deleteRecords = (textDetails) => {
    confirm.require({
        target: event.currentTarget,
        message: "Do you want to Proceed?",
        icon: 'pip pi-exclamation-circle',
        rejectProps: {
            label: 'Cancel',
            severity: 'secondary',
            outlined: true
        },
        acceptProps: {
            label: 'Delete Records',
            severity: 'danger',
        },
        accept: () => {
            axios.delete(`/deleteTextRecords/${textDetails.id}`)
                .then((response) => {
                    toast.add({ severity: 'success', summary: 'Ingestion Summary', detail: 'Deletion IN Progress', life: 6000 });
                    console.log("Deletion info: ", response.data)

                })
                .catch((error) => {
                    console.error('Error while ingestion', error)
                    toast.add({ severity: 'error', summary: 'Error Summary', detail: 'Deletion Failed', life: 6000 });
                })
        },
        reject: () => {
            toast.add({ severity: 'error', summary: 'Rejected', detail: 'You have rejected', life: 3000 })
        }
    })
};
//format date
const getCustomDatewithAllResponse = (data) => {
    return [...(data || [])].map((d) => {
        d.ingestionDateFormat = new Date(d.ingestionDateFormat);
        return d;
    })
}

function formatDate(dateString) {
    // Parse the date string using moment
    return moment(dateString).format('MM/DD/YYYY');
}
</script>
<template>
    <div>
        <div content-section introduction big-title>
            <div class="feature-intro">
                <h1>Texts <span>DataTable</span></h1>
            </div>
        </div>
        <div class="card">
            <Toast />
            <ConfirmPopup></ConfirmPopup>
            <Toolbar class="mb-6">

            </Toolbar>
            <DataTable :value="textInfo" :filters="filters">
                <Column field="id" header="Id">
                    {{ id }}
                </Column>
                <Column field="name" header="Name">
                    <template #body="{ data }">
                        {{ data.name }}
                    </template>
                    <template #filter="{ filterModel, filterCallback }">
                        <InputText v-model="filterModel.value" type="text" @input="filterCallback()"
                            placeholder="Search By Name"></InputText>
                    </template>
                </Column>
                <Column field="KsApplicationName" header="ApplicationName">
                    <template #body="{ data }">
                        {{ data.ingestionInfo.metadata.KsApplicationName }}
                    </template>
                </Column>
                <Column field="ingestionDate" header="Date">
                    <template #body="{ data }">
                        {{ formatDate(data.ingestionDate) }}
                    </template>
                </Column>
                <Column :exportable="false" style="min-width: 12rem">
                    <template #body="slotProps">
                        <Button text raised rounded severity="info" type="button" class="mr-2" icon="pi pi-trash"
                            @click="deleteRecords(slotProps.data)" v-tooltip.top="'Delete the records'">
                        </Button>
                    </template>
                </Column>
            </DataTable>
        </div>
    </div>
</template>