<template>
    <div>
        <manage-sidebar />
        <div class="page-wrapper">
            <div class="page-header d-print-none">
                <div class="container-fluid">
                    <div class="row g-2 align-items-center">
                        <div class="col">
                            <div class="page-pretitle">Logs</div>
                            <h2 class="page-title">Person Detection Logs</h2>
                        </div>
                        <div class="col-auto">
                            <button class="btn btn-primary" @click="refreshLogs" :disabled="loading">
                                <span v-if="loading">
                                    <i class="fa fa-spinner fa-spin me-2"></i> Refreshing...
                                </span>
                                <span v-else>
                                    <i class="fa fa-refresh me-2"></i> Refresh
                                </span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="page-body">
                <div class="container-fluid">
                    <div class="card">
                        <div class="card-body" style="min-height: 78vh;">
                            <div v-if="loading" class="text-center my-5">
                                <i class="fa fa-spinner fa-spin fa-3x"></i>
                                <p class="mt-4">Loading data, please wait...</p>
                            </div>
                            <div v-else>
                                <div class="row">
                                    <div class="col pb-2">
                                        Results: <strong>{{ totalResults }}</strong> data
                                    </div>
                                </div>
                                <div class="row mb-2">
                                    <div class="col">
                                        <label for="itemsPerPage" class="me-2">Show:</label>
                                        <select id="itemsPerPage" v-model="itemsPerPage" @change="paginateData"
                                            class="form-select d-inline-block w-auto">
                                            <option :value="10">10</option>
                                            <option :value="15">15</option>
                                            <option :value="25">25</option>
                                            <option :value="50">50</option>
                                            <option :value="100">100</option>
                                        </select>
                                    </div>
                                    <div class="col-lg-4">
                                        <input type="text" v-model="searchQuery" @input="searchLogs"
                                            placeholder="Search logs..." class="form-control" />
                                    </div>
                                </div>
                                <div class="table-responsive">
                                    <table class="datatable table table-hover table-borderd">
                                        <thead>
                                            <tr>
                                                <th>Datetime (WIB)</th>
                                                <th>Name</th>
                                                <!-- <th>Confidence</th> -->
                                                <th>Camera Number</th>
                                            </tr>
                                        </thead>

                                        <tbody>
                                            <tr v-for="(log, index) in paginatedLogs" :key="log.id">
                                                <td style="min-width: 160px;">
                                                    {{ log.created_at }}
                                                </td>
                                                <td style="min-width: 200px;">
                                                    {{ log.name }}
                                                </td>
                                                <!-- <td>
                                                    {{ log.confidence !== null ? (log.confidence * 100).toFixed(2) + "%" : "N/A" }}
                                                </td> -->
                                                <td>
                                                    Camera {{ log.camera }}
                                                </td>
                                            </tr>
                                        </tbody>

                                    </table>
                                </div>

                                <nav aria-label="Page navigation">
                                    <ul class="pagination justify-content-center">
                                        <li class="page-item" :class="{ disabled: currentPage === 1 }">
                                            <button class="page-link" @click="changePage(1)">First</button>
                                        </li>
                                        <li class="page-item" :class="{ disabled: currentPage === 1 }">
                                            <button class="page-link"
                                                @click="changePage(currentPage - 1)">Previous</button>
                                        </li>
                                        <!-- Render angka halaman -->
                                        <li class="page-item" v-for="page in pageRange" :key="page"
                                            :class="{ active: currentPage === page }">
                                            <button class="page-link" @click="changePage(page)">{{ page }}</button>
                                        </li>
                                        <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                                            <button class="page-link" @click="changePage(currentPage + 1)">Next</button>
                                        </li>
                                        <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                                            <button class="page-link" @click="changePage(totalPages)">Last</button>
                                        </li>
                                    </ul>
                                </nav>


                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <manage-footer />
        </div>
    </div>
</template>

<script>
import ManageSidebar from "@/views/manage/sidebar.vue";
import ManageFooter from "@/views/manage/footer.vue";
import axios from "axios";

export default {
    name: "DetectionLogs",
    components: { ManageSidebar, ManageFooter },
    data() {
        return {
            allLogs: [], // Full dataset
            paginatedLogs: [], // Data displayed on current page
            currentPage: 1,
            totalPages: 1,
            itemsPerPage: 10,
            totalResults: 0,
            searchQuery: "",
            loading: false, // Tracks loading state
        };
    },
    computed: {
        pageRange() {
            const range = [];
            const start = Math.max(1, this.currentPage - 2); // Menampilkan 2 halaman sebelumnya
            const end = Math.min(this.totalPages, this.currentPage + 2); // Menampilkan 2 halaman setelahnya
            for (let i = start; i <= end; i++) {
                range.push(i);
            }
            return range;
        },
    },
    methods: {
        async fetchLogs() {
            this.loading = true;
            try {
                const response = await axios.get("/api/proxy/object-detected");
                this.allLogs = response.data.data.sort(
                    (a, b) => new Date(b.created_at) - new Date(a.created_at)
                );
                this.paginateData();
                this.totalResults = this.allLogs.length;
                this.totalPages = Math.ceil(this.allLogs.length / this.itemsPerPage);
            } catch (error) {
                console.error("Error fetching logs:", error);
            } finally {
                this.loading = false;
            }
        },
        paginateData() {
            const start = (this.currentPage - 1) * this.itemsPerPage;
            const end = start + this.itemsPerPage;
            this.paginatedLogs = this.allLogs.slice(start, end);
        },
        changePage(page) {
            if (page > 0 && page <= this.totalPages) {
                this.currentPage = page;
                this.paginateData();
            }
        },
        refreshLogs() {
            this.fetchLogs();
        },
        searchLogs() {
            if (this.searchQuery.trim() !== "") {
                this.allLogs = this.allLogs.filter((log) =>
                    log.name.toLowerCase().includes(this.searchQuery.toLowerCase())
                );
            } else {
                this.fetchLogs();
            }
            this.currentPage = 1;
            this.paginateData();
        },
    },
    mounted() {
        this.fetchLogs();
    },
};
</script>


<style scoped>
.text-center {
    margin-top: 20px;
}

.fa-spinner {
    color: #007bff;
}
</style>
