<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">Manage Subjects</h2>
                        </div>
                        <div class="col-auto ms-auto">
                            <button class="btn btn-primary" @click="fetchSubjects">
                                <i class="fa fa-refresh me-1"></i> Refresh
                            </button>
                            <button class="btn btn-success ms-2" data-bs-toggle="modal"
                                data-bs-target="#addSubjectModal">
                                <i class="fa fa-plus me-1"></i> Add
                            </button>
                        </div>

                    </div>
                </div>
            </div>
            <div class="page-body" style="min-height: 79vh">
                <div class="container-fluid">
                    <div class="card">
                        <div class="card-body">
                            <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>
                                <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Subject Name / ID</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr v-for="(subject, index) in subjects" :key="index">
                                            <td>{{ index + 1 }}</td>
                                            <td style="width: 90%;"> {{ subject }}</td>
                                            <td class="d-flex align-items-center list-unstyled">
                                                <button class="px-2 py-1 btn btn-outline-azure me-1"
                                                    @click="openRenameModal(subject)">
                                                    <i class="fa fa-edit me-1"></i> Rename
                                                </button>
                                                <button class="px-2 py-1 btn btn-outline-danger"
                                                    @click="deleteSubject(subject)">
                                                    <i class="fa fa-trash me-1"></i> Delete
                                                </button>
                                            </td>

                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <manage-footer />

        <!-- Rename Subject Modal -->
        <div class="modal fade" id="renameModal" tabindex="-1" aria-labelledby="renameModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="renameModalLabel">Rename Subject</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="newSubjectName" class="form-label">New Subject Name</label>
                            <input type="text" id="newSubjectName" class="form-control" v-model="newSubjectName" />
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">CANCEL</button>
                        <button type="button" class="btn btn-success" @click="renameSubject" :disabled="isSubmitting">
                            <span v-if="isSubmitting">
                                <i class="fa fa-spinner fa-spin me-2"></i> Saving...
                            </span>
                            <span v-else>
                                Save
                            </span>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal fade" id="addSubjectModal" tabindex="-1" aria-labelledby="addSubjectModalLabel"
            aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addSubjectModalLabel">Add New Subject</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="newSubjectInput" class="form-label">Subject Name</label>
                            <input type="text" id="newSubjectInput" class="form-control" v-model="newSubject" />
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-success" @click="addSubject" :disabled="isSubmitting">
                            <span v-if="isSubmitting">
                                <i class="fa fa-spinner fa-spin me-2"></i> Saving...
                            </span>
                            <span v-else>
                                Save
                            </span>
                        </button>
                    </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 { mapGetters, mapActions } from "vuex";
import Swal from "sweetalert2";

export default {
    name: "ManageSubjects",
    components: {
        ManageSidebar,
        ManageFooter,
    },
    data() {
        return {
            subjects: [],
            loading: false,
            selectedSubject: null, // Subject selected for renaming
            newSubjectName: "", // New name for the subject
            newSubject: "",
            isSubmitting: false, // Track submit status
        };
    },
    computed: {
        ...mapGetters(["authToken"]),
    },
    methods: {
        ...mapActions(["setAuthToken", "logout"]),
        setupInterceptors() {
            axios.interceptors.response.use(
                (response) => response,
                async (error) => {
                    if (error.response.status === 401) {
                        // Handle token expiration
                        try {
                            const refreshTokenResponse = await axios.post("/api/refresh-token", {
                                token: this.authToken,
                            });
                            const newToken = refreshTokenResponse.data.token;
                            this.setAuthToken(newToken);
                            error.config.headers.Authorization = `Bearer ${newToken}`;
                            return axios(error.config); // Retry original request
                        } catch (refreshError) {
                            this.logout();
                            this.$router.push({ name: "Login" });
                        }
                    }
                    return Promise.reject(error);
                }
            );
        },
        async fetchSubjects() {
            this.loading = true;
            try {
                const response = await axios.get("/api/api-cpf/subjects");
                this.subjects = response.data.subjects || [];
            } catch (error) {
                console.error("Error fetching subjects:", error);
                this.subjects = [];
            } finally {
                this.loading = false;
            }
        },
        openRenameModal(subject) {
            this.selectedSubject = subject;
            this.newSubjectName = subject;
            const modal = new bootstrap.Modal(document.getElementById("renameModal"));
            modal.show();
        },
        async addSubject() {
            if (!this.newSubject) {
                Swal.fire({
                    icon: "warning",
                    title: "Validation Error",
                    text: "Subject name cannot be empty.",
                });
                return;
            }

            this.isSubmitting = true; // Start loading indicator
            try {
                await axios.post("/api/api-cpf/subjects", { subject: this.newSubject });
                Swal.fire({
                    icon: "success",
                    title: "Success",
                    text: "Subject added successfully.",
                });
                this.fetchSubjects(); // Refresh subject list
            } catch (error) {
                console.error("Error adding subject:", error);
                Swal.fire({
                    icon: "error",
                    title: "Error",
                    text: "Failed to add subject. Please try again.",
                });
            } finally {
                this.isSubmitting = false; // Stop loading indicator
                this.newSubject = ""; // Reset input
                const modal = bootstrap.Modal.getInstance(document.getElementById("addSubjectModal"));
                modal.hide();
            }
        },

        async renameSubject() {
            if (!this.newSubjectName || this.newSubjectName === this.selectedSubject) {
                Swal.fire({
                    icon: "warning",
                    title: "No changes",
                    text: "The new subject name must be different.",
                });
                return;
            }

            this.isSubmitting = true; // Start loading indicator
            try {
                await axios.put(`/api/api-cpf/subjects/${this.selectedSubject}`, {
                    subject: this.newSubjectName,
                });
                Swal.fire({
                    icon: "success",
                    title: "Success",
                    text: "Subject renamed successfully.",
                });
                this.fetchSubjects();
            } catch (error) {
                console.error("Error renaming subject:", error);
                Swal.fire({
                    icon: "error",
                    title: "Error",
                    text: "Failed to rename subject. Please try again.",
                });
            } finally {
                this.isSubmitting = false; // Stop loading indicator
                const modal = bootstrap.Modal.getInstance(document.getElementById("renameModal"));
                modal.hide();
            }
        },

        async deleteSubject(subject) {
            const result = await Swal.fire({
                title: "Are you sure?",
                text: `You are about to delete the subject: "${subject}"`,
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
                confirmButtonText: "Yes, delete it!",
            });

            if (result.isConfirmed) {
                try {
                    await axios.delete(`/api/api-cpf/subjects/${subject}`);
                    Swal.fire({
                        icon: "success",
                        title: "Deleted",
                        text: "Subject deleted successfully.",
                    });
                    this.fetchSubjects();
                } catch (error) {
                    console.error("Error deleting subject:", error);
                    Swal.fire({
                        icon: "error",
                        title: "Error",
                        text: "Failed to delete subject. Please try again.",
                    });
                }
            }
        },
    },
    mounted() {
        this.setupInterceptors();
        this.fetchSubjects();
    },
};
</script>
