<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">Manage</div>
                            <h2 class="page-title">Manajemen Data / CCTV</h2>
                        </div>

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

            <div class="page-body">
                <div class="container-fluid">
                    <div class="row row-deck row-cards">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body" style="min-height: 78vh">
                                    <div class="row">
                                        <div class="col">
                                            <h3>
                                                Lists CCTV
                                            </h3>
                                        </div>
                                        <div class="col-auto ms-auto">
                                            <button class="btn py-1 px-2 btn-primary me-1" @click="fetchCCTVFeeds">
                                                <i class="fa fa-refresh me-1"></i>
                                                Refresh
                                            </button>
                                            <button class="btn py-1 px-2 btn-success" data-bs-toggle="modal"
                                                data-bs-target="#addModalForm">
                                                <i class="fa fa-plus me-1"></i> Add Data
                                            </button>
                                        </div>
                                    </div>
                                    <div class="row justify-content-between">
                                        <div class="col-1">
                                            <label for="itemsPerPage" class="me-2">Show:</label>
                                            <select id="itemsPerPage" v-model="itemsPerPage" @change="fetchCCTVFeeds"
                                                class="form-select d-inline-block w-100">
                                                <option :value="5">5</option>
                                                <option :value="10">10</option>
                                                <option :value="20">20</option>
                                                <option :value="50">50</option>
                                                <option :value="75">75</option>
                                                <option :value="100">100</option>
                                            </select>
                                        </div>
                                        <div class="col-lg-6 col-auto">
                                            <label for="" class="me-2">Cari CCTV:</label>
                                            <input type="text" v-model="searchQuery" @input="fetchCCTVFeeds"
                                                placeholder="Keyword ..." class="form-control me-2 w-100">
                                        </div>
                                    </div>

                                    <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="mt-1">
                                            Results: {{ totalResults }} data
                                        </div>
                                        <div class="table-responsive mt-0">
                                            <table id="datatable" class="table table-bordered table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>#</th>
                                                        <th>Camera Name</th>
                                                        <th>URL / IP Address</th>
                                                        <th>URL / IP Address Intranet</th>
                                                        <th>Building</th>
                                                        <th>Office</th>
                                                        <th>Resolution</th>
                                                        <th>Status</th>
                                                        <th>Created At</th>
                                                        <th>Updated At</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr v-for="(cctv, index) in cctvFeeds" :key="cctv.id">
                                                        <td class="vertical-align-middle">
                                                            {{ index + 1 + (currentPage - 1) * itemsPerPage }}
                                                        </td>
                                                        <td class="vertical-align-middle" style="min-width: 250px;">
                                                            {{ cctv.camera_name }}
                                                        </td>
                                                        <td class="vertical-align-middle" style="width: 200px;">
                                                            <a :href="cctv.ip_address" target="_blank">
                                                                {{ cctv.ip_address }}
                                                            </a>
                                                        </td>
                                                        <td class="vertical-align-middle" style="width: 200px;">
                                                            <a :href="cctv.ip_address_intranet" target="_blank">
                                                                {{ cctv.ip_address_intranet }}
                                                            </a>
                                                        </td>
                                                        <td class="vertical-align-middle" style="min-width: 160px;">
                                                            {{ cctv.building.building_name }}
                                                        </td>
                                                        <td class="vertical-align-middle" style="min-width: 350px;">
                                                            {{ cctv.building.office.office_name }}
                                                        </td>
                                                        <td class="vertical-align-middle">{{ cctv.resolution }}</td>
                                                        <td class="vertical-align-middle">
                                                            <span
                                                                :class="{ 'badge bg-success': cctv.status == '1', 'badge bg-secondary': cctv.status == '0' }">
                                                                {{ cctv.status == '1' ? 'Aktif' : 'Tidak Aktif' }}
                                                            </span>
                                                        </td>
                                                        <td style="min-width: 180px;">
                                                            {{ formatDate(cctv.created_at) }}
                                                        </td>
                                                        <td style="min-width: 180px;">
                                                            {{ formatDate(cctv.updated_at) }}
                                                        </td>
                                                        <td style="min-width: 180px;">
                                                            <button class="px-2 py-1 btn btn-outline-warning me-1"
                                                                @click="editCCTV(cctv)">
                                                                <i class="fa fa-edit me-1"></i>
                                                                Edit
                                                            </button>
                                                            <button class="px-2 py-1 btn btn-outline-danger"
                                                                @click="deleteCCTVFeed(cctv.id)">
                                                                <i class="fa fa-trash me-1"></i>
                                                                Delete
                                                            </button>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>

                                    <nav aria-label="Page navigation" class="mt-3">
                                        <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>
                                            <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>
            </div>
            <manage-footer />
        </div>

        <!-- Add Modal -->
        <div class="modal fade" id="addModalForm" tabindex="-1" aria-labelledby="addModalFormLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addModalFormLabel">Add CCTV</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="addCCTVFeed">
                            <div class="mb-3">
                                <label for="camera_name" class="form-label">Camera Name</label>
                                <input type="text" class="form-control" v-model="addForm.camera_name" required
                                    placeholder="Example : Camera 1 - Ruang Meeting" />
                            </div>
                            <div class="mb-3">
                                <label for="building_id" class="form-label">Building</label>
                                <select class="form-select" v-model="addForm.building_id" required>
                                    <option disabled value="">Select Building</option>
                                    <template v-for="office in groupedBuildings" :key="office.office_id">
                                        <optgroup :label="office.office_name">
                                            <option v-for="building in office.buildings" :key="building.id"
                                                :value="building.id">
                                                {{ building.building_name }}
                                            </option>
                                        </optgroup>
                                    </template>
                                </select>
                            </div>

                            <div class="mb-3">
                                <label for="ip_address" class="form-label">IP Address</label>
                                <input type="text" class="form-control" v-model="addForm.ip_address" required
                                    placeholder="Example : https://cctv1.uidkalbar.com/stream" />
                            </div>
                            <div class="mb-3">
                                <label for="ip_address_intranet" class="form-label">IP Address Intranet</label>
                                <input type="text" class="form-control" v-model="addForm.ip_address_intranet"
                                    placeholder="Example: http://192.168.1.76:8888/stream" />
                            </div>
                            <div class="mb-3">
                                <label for="resolution" class="form-label">Resolution</label>
                                <input type of="text" class="form-control" v-model="addForm.resolution"
                                    placeholder="Example : 720p">
                            </div>
                            <div class="mb-3">
                                <label for="status" class="form-label">Status</label>
                                <select class="form-control" v-model="addForm.status">
                                    <option value="1">Aktif</option>
                                    <option value="0">Tidak Aktif</option>
                                </select>
                            </div>
                            <div class="form-group mt-5 d-flex justify-content-end">
                                <button type="button" class="btn btn-secondary me-2" data-bs-dismiss="modal">
                                    <i class="fa fa-times me-1"></i>
                                    Close
                                </button>
                                <button type="submit" class="btn btn-success" :disabled="isSaving">
                                    <span v-if="isSaving" class="spinner-border spinner-border-sm me-2" role="status"
                                        aria-hidden="true"></span>
                                    <span v-if="!isSaving">
                                        <i class="fa fa-save me-1"></i>
                                        Submit
                                    </span>
                                    <span v-else>
                                        <i class="fa fa-spinner me-1"></i>
                                        Saving...
                                    </span>
                                </button>

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

        <!-- Edit Modal -->
        <div class="modal fade" id="editModalForm" tabindex="-1" aria-labelledby="editModalFormLabel"
            aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editModalFormLabel">Edit CCTV</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="updateCCTVFeed">
                            <div class="mb-3">
                                <label for="camera_name" class="form-label">Camera Name</label>
                                <input type="text" class="form-control" v-model="editForm.camera_name" required>
                            </div>
                            <div class="mb-3">
                                <label for="building_id" class="form-label">Building</label>
                                <select class="form-select" v-model="editForm.building_id" required>
                                    <option disabled value="">Select Building</option>
                                    <template v-for="office in groupedBuildings" :key="office.office_id">
                                        <optgroup :label="office.office_name">
                                            <option v-for="building in office.buildings" :key="building.id"
                                                :value="building.id">
                                                {{ building.building_name }}
                                            </option>
                                        </optgroup>
                                    </template>
                                </select>
                            </div>

                            <div class="mb-3">
                                <label for="ip_address" class="form-label">IP Address</label>
                                <input type="text" class="form-control" v-model="editForm.ip_address" required>
                            </div>
                            <div class="mb-3">
                                <label for="ip_address_intranet" class="form-label">IP Address Intranet</label>
                                <input type="text" class="form-control" v-model="editForm.ip_address_intranet"
                                    placeholder="Example: http://192.168.1.76:8888/stream" />
                            </div>

                            <div class="mb-3">
                                <label for="resolution" class="form-label">Resolution</label>
                                <input type="text" class="form-control" v-model="editForm.resolution">
                            </div>

                            <div class="mb-3">
                                <label for="status" class="form-label">Status</label>
                                <select class="form-control" v-model="editForm.status">
                                    <option value="1">Aktif</option>
                                    <option value="0">Tidak Aktif</option>
                                </select>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                <!-- Edit CCTV Modal Submit Button -->
                                <button type="submit" class="btn btn-primary" :disabled="isSaving">
                                    <span v-if="isSaving" class="spinner-border spinner-border-sm me-2" role="status"
                                        aria-hidden="true"></span>
                                    <span v-if="!isSaving">Update CCTV</span>
                                    <span v-else>Saving...</span>
                                </button>

                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script type="module">
import ManageSidebar from '@/views/manage/sidebar.vue';
import ManageFooter from '@/views/manage/footer.vue';
import axios from 'axios';
import Swal from 'sweetalert2';
import { mapGetters, mapActions } from 'vuex';

export default {
    name: 'ManageCCTV',
    components: { ManageSidebar, ManageFooter },
    data() {
        return {
            cctvFeeds: [],
            groupedBuildings: [],
            currentPage: 1,
            totalPages: 1,
            totalResults: 0,
            searchQuery: '',
            itemsPerPage: 10,
            loading: false,
            noData: false,
            isSaving: false,
            addForm: this.getEmptyForm(),
            editForm: this.getEmptyForm(),
        };
    },
    computed: {
        ...mapGetters(['user', 'authToken', 'refreshToken']),
        pageRange() {
            const range = [];
            const start = Math.max(1, this.currentPage - 2);
            const end = Math.min(this.totalPages, start + 4);

            for (let i = start; i <= end; i++) {
                range.push(i);
            }
            return range;
        },
    },
    methods: {
        ...mapActions(['logout', 'setAuthToken', 'setRefreshToken']),

        getEmptyForm() {
            return {
                camera_name: '',
                ip_address: '',
                ip_address_intranet: '',
                resolution: '',
                status: 1,
                building_id: '',
            };
        },
        async fetchBuildingLists() {
            try {
                const { data } = await axios.get('/api/office/building-grouped-by-office', {
                    headers: { Authorization: `Bearer ${this.authToken}` },
                });
                this.groupedBuildings = data;
            } catch (error) {
                Swal.fire('Error', 'Failed to fetch buildings and offices.', 'error');
                if (error.response && error.response.status === 401) {
                    await this.handleTokenRefresh();
                }
            }
        },

        async fetchCCTVFeeds(page = 1) {
            this.loading = true;
            this.noData = false;
            try {
                const { data } = await axios.get('/api/cctvs', {
                    headers: { Authorization: `Bearer ${this.authToken}` },
                    params: {
                        page,
                        search: this.searchQuery,
                        itemsPerPage: this.itemsPerPage
                    },
                });
                this.cctvFeeds = data.data || [];
                this.currentPage = data.current_page || 1;
                this.totalPages = data.last_page || 1;
                this.totalResults = data.total || 0;
                this.noData = this.cctvFeeds.length === 0;
            } catch (error) {
                Swal.fire('Error', 'Failed to fetch CCTV feeds.', 'error');
                if (error.response && error.response.status === 401) {
                    await this.handleTokenRefresh();
                }
            } finally {
                this.loading = false;
            }
        },
        async deleteCCTVFeed(id) {
            try {
                const result = await Swal.fire({
                    title: 'Delete?',
                    text: 'Are you sure you want to delete this CCTV feed?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, delete it!',
                });

                if (result.isConfirmed) {
                    await axios.delete(`/api/cctvs/${id}`, {
                        headers: { Authorization: `Bearer ${this.authToken}` },
                    });
                    Swal.fire('Deleted!', 'CCTV feed has been deleted.', 'success');
                    this.fetchCCTVFeeds(this.currentPage);
                }
            } catch (error) {
                Swal.fire('Error', 'Failed to delete CCTV feed.', 'error');
                if (error.response && error.response.status === 401) {
                    await this.handleTokenRefresh();
                }
            }
        },
        editCCTV(cctv) {
            this.editForm = { ...cctv };
            new bootstrap.Modal(document.getElementById('editModalForm')).show();
        },
        async updateCCTVFeed() {
            this.isSaving = true;
            try {
                await axios.put(`/api/cctvs/${this.editForm.id}`, this.editForm, {
                    headers: { Authorization: `Bearer ${this.authToken}` },
                });
                Swal.fire('Updated', 'CCTV updated successfully!', 'success');
                this.fetchCCTVFeeds(this.currentPage);
                this.editForm = this.getEmptyForm();
                const modal = bootstrap.Modal.getInstance(document.getElementById('editModalForm'));
                modal.hide();
            } catch (error) {
                Swal.fire('Error', 'Failed to update CCTV feed.', 'error');
                if (error.response && error.response.status === 401) {
                    await this.handleTokenRefresh();
                }
            } finally {
                this.isSaving = false;
            }
        },
        async addCCTVFeed() {
            this.isSaving = true;
            try {
                await axios.post('/api/cctvs', this.addForm, {
                    headers: { Authorization: `Bearer ${this.authToken}` },
                });
                Swal.fire('Success', 'CCTV added successfully!', 'success');
                this.fetchCCTVFeeds(this.currentPage);
                this.addForm = this.getEmptyForm();
                const modal = bootstrap.Modal.getInstance(document.getElementById('addModalForm'));
                modal.hide();
            } catch (error) {
                Swal.fire('Error', 'Failed to add CCTV feed.', 'error');
                if (error.response && error.response.status === 401) {
                    await this.handleTokenRefresh();
                }
            } finally {
                this.isSaving = false;
            }
        },
        changePage(page) {
            this.currentPage = page;
            this.fetchCCTVFeeds(page);
        },
        async handleTokenRefresh() {
            try {
                const refresh_token = this.refreshToken;
                if (!refresh_token) throw new Error('No refresh token available');
                const response = await axios.post('/api/refresh-token', { token: refresh_token });
                const { token, refresh_token: new_refresh_token } = response.data;
                this.setAuthToken(token);
                this.setRefreshToken(new_refresh_token);
                this.setAxiosDefaults(token);
                return token;
            } catch (error) {
                this.logout();
            }
        },
        setupAxiosInterceptors() {
            axios.interceptors.response.use(
                response => response,
                async error => {
                    const { config, response: { status } } = error;
                    if (status === 401 && !config._retry) {
                        config._retry = true;
                        const newToken = await this.handleTokenRefresh();
                        if (newToken) {
                            config.headers['Authorization'] = `Bearer ${newToken}`;
                            return axios(config);
                        }
                    }
                    return Promise.reject(error);
                }
            );
        },
        logout() {
            this.$store.dispatch('logout');
            this.clearSession();
        },
        clearSession() {
            sessionStorage.removeItem('authToken');
            sessionStorage.removeItem('refreshToken');
            sessionStorage.removeItem('user');
            localStorage.removeItem('authToken');
            localStorage.removeItem('refreshToken');
            localStorage.removeItem('user');
        },
        setAxiosDefaults(token) {
            axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        },
        showSuccessAlert(message) {
            this.$swal.fire({
                icon: 'success',
                title: message,
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000
            });
        },
        showErrorAlert(message) {
            this.$swal.fire({
                icon: 'error',
                title: message,
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000
            });
        },
        formatDate(dateString) {
            if (!dateString) return '-';
            return new Intl.DateTimeFormat('id-ID', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false, // Gunakan format 24 jam
                timeZone: 'Asia/Jakarta' // Pastikan sesuai zona waktu Indonesia
            }).format(new Date(dateString));
        },
    },
    mounted() {
        if (!this.user || !this.authToken) {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'You do not have access. Please log in first.',
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000
            }).then(() => {
                this.clearSession();
                this.logout();
            });
        } else {
            this.fetchCCTVFeeds();
            this.fetchBuildingLists();

        }
        this.setupAxiosInterceptors();
    },
};
</script>
