<template>
    <div>
        <div v-if="isSaving" class="loading-overlay">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
        </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">CCTV Area</h2>
                        </div>
                        <div class="col-auto ms-auto">
                            <button class="btn btn-primary me-2" @click="fetchAreas">
                                <i class="fa fa-refresh me-1"></i>
                                Refresh
                            </button>
                            <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addModalForm">
                                <i class="fa fa-plus me-1"></i> Add
                            </button>
                        </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">
                                    <div v-if="loading" class="text-center">
                                        Loading...
                                    </div>
                                    <div v-else>
                                        <div class="row mb-3">
                                            <div class="col">
                                                <label for="itemsPerPage" class="me-2">Show:</label>
                                                <select id="itemsPerPage" v-model="itemsPerPage" @change="fetchAreas"
                                                    class="form-select d-inline-block w-auto">
                                                    <option :value="5">5</option>
                                                    <option :value="10">10</option>
                                                    <option :value="20">20</option>
                                                    <option :value="50">50</option>
                                                </select>
                                            </div>
                                            <div class="col-lg-4">
                                                <input type="text" v-model="searchQuery" @input="fetchAreas"
                                                    placeholder="Search data ..." class="form-control" />
                                            </div>
                                        </div>
                                        <div class="table-responsive">
                                            <table class="table table-hover table-striped table-borderless">
                                                <thead>
                                                    <tr>
                                                        <th>#</th>
                                                        <th>Area Name</th>
                                                        <th>Status</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr v-for="(area, index) in areas" :key="area.id">
                                                        <td>{{ index + 1 + (currentPage - 1) * itemsPerPage }}</td>
                                                        <td style="width: 80%;">
                                                            {{ area.area_name }}
                                                        </td>
                                                        <td class="vertical-align-middle">
                                                            <span
                                                                :class="{ 'badge bg-success': area.status === '1', 'badge bg-secondary': area.status === '0' }">
                                                                {{ area.status === '1' ? 'Aktif' : 'Tidak Aktif' }}
                                                            </span>
                                                        </td>
                                                        <td style="min-width: 200px;">
                                                            <button class="px-2 py-0 btn btn-outline-warning me-1"
                                                                @click="editArea(area)">
                                                                <i class="fa fa-edit me-1"></i>
                                                                Edit
                                                            </button>
                                                            <button class="px-2 py-0 btn btn-outline-danger"
                                                                @click="deleteArea(area.id)">
                                                                <i class="fa fa-trash me-1"></i>
                                                                Delete
                                                            </button>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                        <nav aria-label="Page navigation">
                                            <ul class="pagination">
                                                <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" :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>
            </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-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addModalFormLabel">Add Area</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="addArea">
                            <div class="mb-3">
                                <label for="area_name" class="form-label">Area Name</label>
                                <input type="text" class="form-control" v-model="addForm.area_name" required>
                            </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="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</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">Add Area</span>
                                    <span v-else>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 Area</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="updateArea">
                            <div class="mb-3">
                                <label for="area_name" class="form-label">Area Name</label>
                                <input type="text" class="form-control" v-model="editForm.area_name" required>
                            </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>
                                <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 Area</span>
                                    <span v-else>Saving...</span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
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: 'ManageCCTVAreas',
    components: { ManageSidebar, ManageFooter },
    data() {
        return {
            areas: [],
            currentPage: 1,
            totalPages: 1,
            totalResults: 0,
            searchQuery: '',
            itemsPerPage: 10,
            loading: false,
            noData: false,
            isSaving: false,
            addForm: { area_name: '', status: 1 },
            editForm: { area_name: '', status: 1 },
        };
    },
    computed: {
        ...mapGetters(['user', 'authToken', 'refreshToken']),
    },
    methods: {
        ...mapActions(['logout', 'setAuthToken', 'setRefreshToken']),
        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);
                }
            );
        },
        clearSession() {
            sessionStorage.clear();
            localStorage.clear();
        },
        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
            });
        },
        async fetchAreas(page = 1) {
            this.loading = true;
            this.noData = false;
            try {
                const { data } = await axios.get('/api/cctv-areas', {
                    headers: { Authorization: `Bearer ${this.authToken}` },
                    params: { page, search: this.searchQuery, itemsPerPage: this.itemsPerPage },
                });
                this.areas = data.data || [];
                this.currentPage = data.current_page || 1;
                this.totalPages = data.last_page || 1;
                this.totalResults = data.total || 0;
                this.noData = this.areas.length === 0;
            } catch (error) {
                console.error('Error fetching areas:', error);
                if (error.response && error.response.status === 401) {
                    await this.handleTokenRefresh();
                }
            } finally {
                this.loading = false;
            }
        },
        async addArea() {
            this.isSaving = true;
            try {
                await axios.post('/api/cctv-areas', this.addForm, {
                    headers: { Authorization: `Bearer ${this.authToken}` },
                });
                $('#addModalForm').modal('hide');
                this.fetchAreas(this.currentPage);
                Swal.fire('Success', 'Area added successfully!', 'success');
                this.addForm = { area_name: '', status: 1 };
            } catch (error) {
                Swal.fire('Error', 'Failed to add area.', 'error');
                if (error.response && error.response.status === 401) {
                    await this.handleTokenRefresh();
                }
            } finally {
                this.isSaving = false;
            }
        },
        async updateArea() {
            this.isSaving = true;
            try {
                await axios.put(`/api/cctv-areas/${this.editForm.id}`, this.editForm, {
                    headers: { Authorization: `Bearer ${this.authToken}` },
                });
                $('#editModalForm').modal('hide');
                this.fetchAreas(this.currentPage);
                Swal.fire('Updated', 'Area updated successfully!', 'success');
                this.editForm = { area_name: '', status: 1 };
            } catch (error) {
                Swal.fire('Error', 'Failed to update area.', 'error');
                if (error.response && error.response.status === 401) {
                    await this.handleTokenRefresh();
                }
            } finally {
                this.isSaving = false;
            }
        },
        async deleteArea(id) {
            const result = await Swal.fire({
                title: 'Delete?',
                text: 'Are you sure you want to delete this area?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!',
            });

            if (result.isConfirmed) {
                try {
                    await axios.delete(`/api/cctv-areas/${id}`, {
                        headers: { Authorization: `Bearer ${this.authToken}` },
                    });
                    this.fetchAreas(this.currentPage);
                    Swal.fire('Deleted!', 'Area has been deleted.', 'success');
                } catch (error) {
                    Swal.fire('Error', 'Failed to delete area.', 'error');
                    if (error.response && error.response.status === 401) {
                        await this.handleTokenRefresh();
                    }
                }
            }
        },
        changePage(page) {
            this.currentPage = page;
            this.fetchAreas(page);
        },
    },
    watch: {
        searchQuery() {
            this.fetchAreas();
        },
    },
    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.logout();
            });
        } else {
            this.fetchAreas();
        }
        this.setupAxiosInterceptors();
    }
};
</script>
