<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">Buildings</h2>
                        </div>
                        <div class="col-auto ms-auto">
                            <button class="btn btn-primary" @click="fetchBuildingData">
                                Refresh
                            </button>
                            <button class="btn btn-success ms-2" data-bs-toggle="modal" data-bs-target="#addModalForm">
                                <i class="fa fa-plus me-2"></i> Add Building
                            </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" 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="table-responsive mt-3">
                                            <table class="table table-hover table-striped">
                                                <thead>
                                                    <tr>
                                                        <th>#</th>
                                                        <th>BUILDING NAME</th>
                                                        <th>OFFICE NAME</th>
                                                        <th>ADDRESS</th>
                                                        <th>STATUS</th>
                                                        <th>TIME CREATED</th>
                                                        <th>TIME UPDATED</th>
                                                        <th>ACTIONS</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr v-for="(building, index) in buildings" :key="building.id">
                                                        <td style="vertical-align: middle;">
                                                            {{ index + 1 + (currentPage - 1) * itemsPerPage }}
                                                        </td>
                                                        <td style=" vertical-align: middle; min-width: 200px;">
                                                            {{ building.building_name }}
                                                        </td>
                                                        <td style="vertical-align: middle; min-width: 350px;">
                                                            {{ building.office ? building.office.office_name : '-' }}
                                                        </td>
                                                        <td style="vertical-align: middle; min-width: 300px;">
                                                            {{ building.address }}
                                                        </td>
                                                        <td style="vertical-align: middle; min-width: 60px;">
                                                            <span
                                                                :class="{ 'badge bg-success': building.status === 1, 'badge bg-secondary': building.status === 0 }">
                                                                {{ building.status === 1 ? 'Aktif' : 'Tidak Aktif' }}
                                                            </span>
                                                        </td>
                                                        <td style="vertical-align: middle; min-width: 200px;">
                                                            {{ new Date(building.created_at).toLocaleString() }}
                                                        </td>
                                                        <td style="vertical-align: middle; min-width: 200px;">
                                                            {{ new Date(building.updated_at).toLocaleString() }}
                                                        </td>
                                                        <td class="d-flex align-items-center">
                                                            <button class="btn px-2 py-1 btn-outline-warning me-1"
                                                                @click="editBuilding(building)">
                                                                <i class="fa fa-edit me-1"></i>Edit
                                                            </button>
                                                            <button class="btn px-2 py-1 btn-outline-danger"
                                                                @click="deleteBuilding(building.id)">
                                                                <i class="fa fa-trash me-1"></i>Delete
                                                            </button>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>

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

        </div>

        <manage-footer />

        <!-- 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 Building</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="addBuilding">
                            <div class="mb-3">
                                <label for="office_id" class="form-label">Office</label>
                                <select class="form-select" v-model="addForm.office_id" required>
                                    <option value="" disabled>Select Office</option>
                                    <option v-for="office in offices" :key="office.id" :value="office.id">
                                        {{ office.office_name }}
                                    </option>
                                </select>
                            </div>

                            <div class="mb-3">
                                <label for="building_name" class="form-label">Building Name</label>
                                <input type="text" class="form-control" v-model="addForm.building_name" required>
                            </div>
                            <div class="mb-3">
                                <label for="address" class="form-label">Address</label>
                                <input type="text" class="form-control" v-model="addForm.address" required>
                            </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>
                            <button type="submit" class="btn btn-success d-block w-100" :disabled="isSaving">
                                <span v-if="isSaving">Saving...</span>
                                <span v-else>
                                    <i class="fa fa-save me-1"></i> Save
                                </span>
                            </button>
                        </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 Building</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="updateBuilding">
                            <div class="mb-3">
                                <label for="office_id" class="form-label">Office</label>
                                <select class="form-select" v-model="editForm.office_id" required>
                                    <option value="" disabled>Select Office</option>
                                    <option v-for="office in offices" :key="office.id" :value="office.id">
                                        {{ office.office_name }}
                                    </option>
                                </select>
                            </div>

                            <div class="mb-3">
                                <label for="building_name" class="form-label">Building Name</label>
                                <input type="text" class="form-control" v-model="editForm.building_name" required>
                            </div>
                            <div class="mb-3">
                                <label for="address" class="form-label">Address</label>
                                <input type="text" class="form-control" v-model="editForm.address" required>
                            </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>
                            <button type="submit" class="btn btn-block btn-success w-100 mt-3" :disabled="isSaving">
                                <span v-if="isSaving">Updating...</span>
                                <span v-else>
                                    <i class="fa fa-save me-1"></i> Update
                                </span>
                            </button>
                        </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: 'BuildingManagement',
    components: { ManageSidebar, ManageFooter },
    data() {
        return {
            offices: [],
            buildings: [],
            currentPage: 1,
            totalPages: 1,
            totalResults: 0,
            itemsPerPage: 10,
            searchQuery: '',
            loading: 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 {
                office_id: '',
                building_name: '',
                address: '',
                status: 1,
            };
        },
        async fetchOfficeData() {
            try {
                const response = await axios.get('/api/offices/list', {
                    headers: { Authorization: `Bearer ${this.authToken}` }
                });

                if (response.data && response.data.success) {
                    this.offices = response.data.data;
                }
            } catch (error) {
                console.error("Error fetching offices:", error);
                Swal.fire('Error', 'Failed to fetch offices.', 'error');
            }
        },
        async fetchBuildingData(page = 1) {
            this.loading = true;
            try {
                const response = await axios.get('/api/buildings', {
                    headers: { Authorization: `Bearer ${this.authToken}` },
                    params: { page, itemsPerPage: this.itemsPerPage, search: this.searchQuery },
                });

                if (response.data && response.data.data) {
                    this.buildings = response.data.data; // Pastikan data dimasukkan ke dalam array buildings
                    this.currentPage = response.data.current_page || 1;
                    this.totalPages = response.data.last_page || 1;
                    this.totalResults = response.data.total || 0;
                } else {
                    this.buildings = []; // Pastikan tidak null
                }
            } catch (error) {
                console.error("Error fetching buildings:", error);
                Swal.fire('Error', 'Failed to fetch buildings.', 'error');
            } finally {
                this.loading = false; // Pastikan loading dihentikan
            }
        },
        async addBuilding() {
            this.isSaving = true;
            try {
                const payload = {
                    ...this.addForm,
                    status: Number(this.addForm.status), // Pastikan status adalah integer
                };

                await axios.post('/api/buildings', payload, {
                    headers: { Authorization: `Bearer ${this.authToken}` },
                });
                Swal.fire('Success', 'Building added successfully!', 'success');
                this.fetchBuildingData();

                this.addForm = this.getEmptyForm();

                // **Tutup modal dengan cara yang benar**
                let modal = bootstrap.Modal.getInstance(document.getElementById('addModalForm'));
                if (modal) modal.hide();

            } catch (error) {
                Swal.fire('Error', 'Failed to add building.', 'error');
                if (error.response && error.response.status === 401) {
                    await this.handleTokenRefresh();
                }
            } finally {
                this.isSaving = false;
            }
        },
        editBuilding(building) {
            this.editForm = { ...building };
            new bootstrap.Modal(document.getElementById('editModalForm')).show();
        },
        async updateBuilding() {
            this.isSaving = true;
            try {
                const payload = {
                    ...this.editForm,
                    status: Number(this.editForm.status), // Pastikan status adalah integer
                };

                await axios.put(`/api/buildings/${this.editForm.id}`, payload, {
                    headers: { Authorization: `Bearer ${this.authToken}` },
                });

                Swal.fire('Success', 'Building updated successfully!', 'success');
                this.fetchBuildingData();
                this.editForm = this.getEmptyForm();

                // **Tutup modal dengan cara yang benar**
                let modal = bootstrap.Modal.getInstance(document.getElementById('editModalForm'));
                if (modal) modal.hide();

            } catch (error) {
                Swal.fire('Error', 'Failed to update building.', 'error');
                if (error.response && error.response.status === 401) {
                    await this.handleTokenRefresh();
                }
            } finally {
                this.isSaving = false;
            }
        },
        async deleteBuilding(id) {
            try {
                const result = await Swal.fire({
                    title: 'Delete?',
                    text: 'Are you sure you want to delete this building?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, delete it!',
                });

                if (result.isConfirmed) {
                    await axios.delete(`/api/buildings/${id}`, {
                        headers: { Authorization: `Bearer ${this.authToken}` },
                    });
                    Swal.fire('Deleted!', 'Building has been deleted.', 'success');
                    this.fetchBuildingData();
                }
            } catch (error) {
                Swal.fire('Error', 'Failed to delete building.', 'error');
                if (error.response && error.response.status === 401) {
                    await this.handleTokenRefresh();
                }
            }
        },
        async changePage(page) {
            if (page > 0 && page <= this.totalPages) {
                this.currentPage = page;
                await this.fetchBuildingData(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) {
                Swal.fire('Error', 'Sesi anda telah habis, silahkan login ulang !', 'error');
                await 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
            });
        },
    },
    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.fetchBuildingData();
            this.fetchOfficeData();
        }
        this.setupAxiosInterceptors();
    }
};
</script>
