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

export default {
    name: 'ManageLayerGeojson',
    components: { ManageSidebar, ManageFooter },
    computed: {
        ...mapGetters(['authToken', 'refreshToken', 'user']),
    },
    data() {
        return {
            geojsonLayers: [],
            currentPage: 1,
            totalPages: 1,
            totalResults: 0,
            searchQuery: '',
            itemsPerPage: 10,
            loading: false,
            noData: false,
            isSaving: false,
            uploadProgress: 0,
            addForm: {
                name: '',
                color: '',
                description: '',
                status: 1,
                file_geojson: null,
            },
            editForm: {},
            currentGeojsonLayerId: null,
            acceptedFileTypes: ['application/geo+json', 'application/json', 'application/vnd.geo+json', 'text/plain'],
        }
    },
    methods: {
        ...mapActions(['logout', 'setAuthToken', 'setRefreshToken']),
        formatDateTime(dateTime) {
            return moment(dateTime).format('DD/MM/YYYY HH:mm:ss');
        },
        resetAddForm() {
            this.addForm = {
                name: '',
                color: '',
                description: '',
                status: 1,
                file_geojson: null,
            };
            this.uploadProgress = 0;
        },
        resetEditForm() {
            this.editForm = {};
        },
        pagesToShow() {
            const pages = [];
            const range = 2; // Jumlah halaman sebelum dan sesudah halaman saat ini
            const total = this.totalPages;
            const current = this.currentPage;

            if (total <= 1) {
                return [1]; // Jika hanya ada satu halaman, tampilkan hanya satu
            }

            // Tambahkan halaman pertama
            pages.push(1);

            // Tampilkan '...' jika jarak lebih dari 2 dari halaman pertama
            if (current - range > 1) {
                pages.push('...');
            }

            // Tampilkan halaman dalam rentang sebelum dan sesudah halaman saat ini
            for (let i = Math.max(2, current - range); i <= Math.min(total - 1, current + range); i++) {
                pages.push(i);
            }

            // Tampilkan '...' jika ada jarak lebih dari 2 ke halaman terakhir
            if (current + range < total - 1) {
                pages.push('...');
            }

            // Tambahkan halaman terakhir
            pages.push(total);

            return pages;
        },
        changePage(page) {
            this.currentPage = page;
            this.fetchUsers(page);
        },

        async fetchGeojsonLayers(page = this.currentPage) {
            this.loading = true;
            this.noData = false;
            try {
                const { data } = await axios.get('/api/geojson-layers', {
                    headers: { Authorization: `Bearer ${this.authToken}` },
                    params: { page, search: this.searchQuery, itemsPerPage: this.itemsPerPage }
                });
                console.log('Data dari API:', data);
                this.geojsonLayers = data.data || [];
                this.currentPage = data.current_page || 1;
                this.totalPages = data.last_page || 1;
                this.totalResults = data.total || 0;
                this.noData = this.geojsonLayers.length === 0;
            } catch (error) {
                console.error('Error fetching geojson layers:', error);
            } finally {
                this.loading = false;
            }
        },
        async addGeojsonLayer() {
            this.isSaving = true;
            const formData = new FormData();
            for (const key in this.addForm) {
                if (this.addForm[key] !== null) {
                    formData.append(key, this.addForm[key]);
                }
            }

            try {
                await axios.post('/api/geojson-layers', formData, {
                    headers: {
                        Authorization: `Bearer ${this.authToken}`,
                        'Content-Type': 'multipart/form-data',
                    },
                    onUploadProgress: (progressEvent) => {
                        this.uploadProgress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                    }
                });
                this.fetchGeojsonLayers();
                this.showSuccessAlert('GeoJSON layer added successfully!');
                this.resetAddForm();
                $('#addModalForm').modal('hide');
            } catch (error) {
                this.showErrorAlert('Failed to save GeoJSON layer. An error occurred!');
                if (error.response && error.response.status === 401) {
                    await this.handleTokenRefresh();
                    this.addGeojsonLayer();
                }
            } finally {
                this.isSaving = false;
            }
        },
        handleFileUpload(event) {
            const file = event.target.files[0];
            const fileExtension = file.name.split('.').pop().toLowerCase();
            if (fileExtension === 'geojson') {
                this.addForm.file_geojson = file;
            } else {
                this.showErrorAlert('Invalid file type. Please upload a valid GeoJSON file.');
                event.target.value = null;
            }
        },
        async deleteGeojsonLayer(id) {
            const result = await Swal.fire({
                title: 'Delete?',
                text: 'Are you sure you want to delete this layer?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it',
                cancelButtonText: 'Cancel'
            });

            if (result.isConfirmed) {
                try {
                    await axios.delete(`/api/geojson-layers/${id}`, {
                        headers: { Authorization: `Bearer ${this.authToken}` }
                    });
                    this.fetchGeojsonLayers(this.currentPage);
                    this.showSuccessAlert('GeoJSON layer deleted successfully!');
                } catch (error) {
                    this.showErrorAlert('Failed to delete GeoJSON layer. An error occurred!');
                }
            }
        },
        editGeojsonLayer(data) {
            this.editForm = { ...data };
            $('#editModalForm').modal('show');
        },
        async updateGeojsonLayer() {
            this.isSaving = true;
            try {
                await axios.put(`/api/geojson-layers/${this.editForm.id}`, this.editForm, {
                    headers: {
                        Authorization: `Bearer ${this.authToken}`,
                    },
                });
                this.fetchGeojsonLayers(this.currentPage);
                this.showSuccessAlert('GeoJSON layer updated successfully!');
                $('#editModalForm').modal('hide');
                this.resetEditForm();
            } catch (error) {
                console.error('Error updating geojson layer:', error);
                Swal.fire('Error!', 'An error occurred!', 'error');
                if (error.response && error.response.status === 401) {
                    await this.handleTokenRefresh();
                    this.updateGeojsonLayer();
                }
            } finally {
                this.isSaving = false;
            }
        },
        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
            });
        },
    },
    watch: {
        itemsPerPage() {
            this.fetchGeojsonLayers();
        },
        searchQuery() {
            this.fetchGeojsonLayers();
        },
    },
    async 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
            });
            this.logout();
        } else {
            this.setupAxiosInterceptors();
            this.fetchGeojsonLayers();
        }
    },
}
</script>


<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">Home</div>
                            <h2 class="page-title">Manage GeoJSON Layers</h2>
                        </div>
                    </div>
                </div>
            </div>
            <div class="page-body" style="min-height: 79vh">
                <div class="container-fluid">
                    <div class="row row-deck row-cards">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <h2 class="mb-1">
                                        <i class="fa fa-map me-1"></i>
                                        List of GeoJSON Layers
                                    </h2>
                                    <hr />
                                    <div class="row justify-content-end mt-1">
                                        <div class="col">
                                            <p class="mt-2 mb-0">
                                                Results: {{ totalResults }} layers
                                            </p>
                                        </div>
                                        <div class="col-auto ms-auto">
                                            <button class="btn btn-primary" @click="fetchGeojsonLayers">
                                                <i class="fa fa-refresh me-1"></i> Refresh
                                            </button>
                                            <button class="ms-1 btn btn-success" data-bs-toggle="modal"
                                                data-bs-target="#addModalForm">
                                                <i class="fa fa-plus me-1"></i>
                                                Add Layer
                                            </button>
                                        </div>
                                    </div>
                                    <div class="row mb-2 pt-2">
                                        <div class="mb-2 col">
                                            <select v-model="itemsPerPage" class="form-select w-auto">
                                                <option v-for="option in [10, 15, 25, 50]" :key="option"
                                                    :value="option">
                                                    {{ option }}
                                                </option>
                                            </select>
                                        </div>
                                        <div class="mb-2 col-lg-4 col-md-4 col-sm-12">
                                            <input type="text" class="form-control" placeholder="Search layers..."
                                                v-model="searchQuery" @input="fetchGeojsonLayers" />
                                        </div>
                                    </div>
                                    <div v-if="loading" class="text-center">
                                        <p>Loading...</p>
                                    </div>
                                    <div v-else>
                                        <div class="table-responsive">
                                            <table class="table table-sm table-bordered table-hover">
                                                <thead>
                                                    <tr class="text-center">
                                                        <th>No</th>
                                                        <th>Name</th>
                                                        <th>Type</th>
                                                        <th>Color</th>
                                                        <th>Description</th>
                                                        <!-- <th>Description</th> -->
                                                        <!-- <th>Description</th> -->
                                                        <th>Status</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody v-if="geojsonLayers.length">
                                                    <tr v-for="(layer, index) in geojsonLayers" :key="layer.id">
                                                        <td class="align-middle text-center">
                                                            {{ index + 1 + (currentPage - 1) * itemsPerPage }}
                                                        </td>
                                                        <td class="align-middle">{{ layer.name }}</td>
                                                        <td class="align-middle">{{ layer.type }}</td>
                                                        <td class="align-middle">
                                                            <div style="display: flex; align-items: center;">
                                                                <span :style="{
                                                                    width: '20px',
                                                                    height: '20px',
                                                                    backgroundColor: layer.color,
                                                                    display: 'inline-block',
                                                                    border: '1px solid #000',
                                                                    marginRight: '8px'
                                                                }">
                                                                </span>
                                                                {{ layer.color }}
                                                            </div>
                                                        </td>
                                                        <td class="align-middle">{{ layer.description }}</td>
                                                        <!-- <td class="align-middle">{{ layer.properties }}</td> -->
                                                        <!-- <td class="align-middle">{{ layer.geometry }}</td> -->
                                                        <td class="align-middle text-center">
                                                            <span
                                                                :class="layer.status === 1 ? 'badge bg-success' : 'badge bg-secondary'">
                                                                {{ layer.status === 1 ? 'Aktif' : 'Tidak Aktif' }}
                                                            </span>
                                                        </td>
                                                        <td class="align-middle text-center">
                                                            <button class="btn px-2 py-1 btn-outline-warning me-1"
                                                                @click="editGeojsonLayer(layer)">
                                                                <i class="fa fa-edit me-2"></i> Edit
                                                            </button>
                                                            <button class="btn px-2 py-1 btn-outline-danger"
                                                                @click="deleteGeojsonLayer(layer.id)">
                                                                <i class="fa fa-trash me-2"></i> Delete
                                                            </button>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                                <tbody v-else>
                                                    <tr>
                                                        <td colspan="6" class="text-center">No layers found!</td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>

                                        <nav class="mt-2">
                                            <ul class="pagination justify-content-center">
                                                <li class="page-item" :class="{ disabled: currentPage === 1 }">
                                                    <a class="page-link" href="#"
                                                        @click.prevent="changePage(1)">First</a>
                                                </li>
                                                <li class="page-item" :class="{ disabled: currentPage === 1 }">
                                                    <a class="page-link" href="#"
                                                        @click.prevent="changePage(currentPage - 1)">Previous</a>
                                                </li>
                                                <li v-for="page in pagesToShow()" :key="page" class="page-item"
                                                    :class="{ active: currentPage === page }">
                                                    <a v-if="page !== '...'" class="page-link" href="#"
                                                        @click.prevent="changePage(page)">{{ page }}</a>
                                                    <span v-else class="page-link">...</span>
                                                </li>
                                                <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                                                    <a class="page-link" href="#"
                                                        @click.prevent="changePage(currentPage + 1)">Next</a>
                                                </li>
                                                <li class="page-item" :class="{ disabled: currentPage === totalPages }">
                                                    <a class="page-link" href="#"
                                                        @click.prevent="changePage(totalPages)">Last</a>
                                                </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 modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addModalFormLabel">Add GeoJSON Layer</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="addGeojsonLayer">
                            <div class="mb-3">
                                <label for="name" class="form-label">Name</label>
                                <input type="text" class="form-control" v-model="addForm.name" required />
                            </div>
                            <div class="mb-3">
                                <label for="color" class="form-label">Color</label>
                                <input type="color" class="form-control" v-model="addForm.color" />
                            </div>
                            <div class="mb-3">
                                <label for="description" class="form-label">Description</label>
                                <textarea class="form-control" v-model="addForm.description"></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="file_geojson" class="form-label">GeoJSON File</label>
                                <input type="file" class="form-control" @change="handleFileUpload"
                                    accept=".json,.geojson,application/geo+json" />
                            </div>
                            <div class="mb-3">
                                <label for="status" class="form-label">Status</label>
                                <select class="form-select" v-model="addForm.status">
                                    <option value="1">Aktif</option>
                                    <option value="0">Tidak Aktif</option>
                                </select>
                            </div>
                            <div v-if="isSaving" class="mb-3">
                                <label class="form-label">Upload Progress</label>
                                <div class="progress">
                                    <div class="progress-bar" role="progressbar"
                                        :style="{ width: uploadProgress + '%' }" :aria-valuenow="uploadProgress"
                                        aria-valuemin="0" aria-valuemax="100">{{ uploadProgress }}%</div>
                                </div>
                            </div>
                            <div class="d-flex justify-content-end">
                                <button type="submit" class="btn btn-success" :disabled="isSaving">
                                    <span v-if="isSaving">
                                        <i class="fa fa-spinner fa-spin me-1"></i>
                                        Saving...
                                    </span>
                                    <span v-else>
                                        <i class="fa fa-arrow-right me-1"></i>
                                        SUBMIT
                                    </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-lg modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editModalFormLabel">Edit GeoJSON Layer</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="updateGeojsonLayer">
                            <div class="mb-3">
                                <label for="name" class="form-label">Name</label>
                                <input type="text" class="form-control" v-model="editForm.name" required />
                            </div>
                            <div class="mb-3">
                                <label for="type" class="form-label">Type</label>
                                <input type="text" class="form-control" v-model="editForm.type" readonly required />
                            </div>
                            <div class="mb-3">
                                <label for="color" class="form-label">Color</label>
                                <input type="color" class="form-control" v-model="editForm.color" />
                            </div>
                            <div class="mb-3">
                                <label for="description" class="form-label">Description</label>
                                <textarea class="form-control" v-model="editForm.description"></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="status" class="form-label">Status</label>
                                <select class="form-select" v-model="editForm.status">
                                    <option value="1">Aktif</option>
                                    <option value="0">Tidak Aktif</option>
                                </select>
                            </div>
                            <div class="d-flex justify-content-end">
                                <button type="submit" class="btn btn-success" :disabled="isSaving">
                                    <span v-if="isSaving">
                                        <i class="fa fa-spinner fa-spin me-1"></i>
                                        Saving...
                                    </span>
                                    <span v-else>
                                        <i class="fa fa-arrow-right me-1"></i>
                                        SUBMIT
                                    </span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

    </div>
</template>
