<template>
    <section class="py-3 px-4">
        <div class="job-popup-container">
            <transition-group name="fade" tag="div">
                <div v-for="msg in jobMessages" :key="msg.id" class="alert alert-info job-popup" role="alert">
                    {{ msg.text }}
                </div>
            </transition-group>
        </div>
        <div class="container-fluid px-0">
            <h1 class="mb-4">🛠 Jobs List:</h1>
            <div v-if="jobs.length === 0" class="text-muted">
                No jobs found.
            </div>
            <div v-else>
                <div v-for="job in jobs" :key="job.id" class="card mb-3">
                    <div class="card-body d-flex justify-content-between align-items-center flex-wrap">
                        <div class="mb-2 mb-md-0">
                            <strong>{{ job.id }}</strong>
                            <span class="badge bg-info text-dark ms-2">{{ job.status }}</span>
                            <span v-if="job.last_run" class="badge bg-light text-muted ms-2">
                                Last run: {{ formatDate(job.last_run) }}
                            </span>
                            <span v-if="job.next_run" class="badge bg-light text-muted ms-2">
                                Next: {{ formatDate(job.next_run) }}
                            </span>
                            <span v-if="job.error" class="badge bg-danger text-light ms-2">
                                ❗ {{ job.error }}
                            </span>
                        </div>
                        <div>
                            <button class="btn btn-sm btn-success me-2" @click="runJobNow(job.id)" :disabled="runningJobs.has(job.id)" type="button">
                                Run now
                                <Play class="icon" size="0.7rem" />
                            </button>
                            <button class="btn btn-sm btn-outline-secondary" @click="toggleDetails(job.id)" type="button">
                                {{ expanded[job.id] ? "Hide" : "Show" }} Data
                            </button>
                        </div>
                    </div>
                    <div v-if="expanded[job.id]" class="card-body pt-0">
                        <pre v-if="job.data" class="bg-light p-3 small rounded overflow-auto">
                            {{ formatJSON(job.data) }}
                        </pre>
                        <p v-else class="fst-italic text-muted mb-0">
                            No cached data available.
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </section>
</template>
<script>
import axios from "axios";
import { Play } from 'lucide-vue-next';
import { popupStore } from '@/stores/popupStore.js';

export default {
    name: "AdminView",
    components: {
        Play
    },
    data() {
        return {
            jobs: [],
            expanded: {},
            runningJobs: new Set(),
        };
    },
    methods: {
        async fetchJobs() {
            const res = await axios.get("https://192.168.70.11:8000/admin/jobs");
            this.jobs = res.data;
        },
        async runJobNow(jobId) {
            if (this.runningJobs.has(jobId)) return;

            this.runningJobs.add(jobId);
            try {
                popupStore.addPopupMessage(`⚙️ Trying to run Job "${jobId}".`);
                const res = await fetch(
                    `https://192.168.70.11:8000/admin/jobs/${jobId}/run`, {
                        method: "POST",
                    }
                );
                if (res.ok) {
                    popupStore.addPopupMessage(`✅ Job "${jobId}" triggered successfully.`);
                } else {
                    const errText = await res.text();
                    popupStore.addPopupMessage(`⚠️ Failed to trigger job "${jobId}": ${errText}`);
                }
                setTimeout(() => this.fetchJobs(), 1000);
            } catch (error) {
                popupStore.addPopupMessage(`❌ Error: ${error.message}`);
            } finally {
                this.runningJobs.delete(jobId);
            }
        },
        toggleDetails(id) {
            this.expanded[id] = !this.expanded[id];
        },
        formatDate(iso) {
            return new Date(iso).toLocaleString();
        },
        formatJSON(obj) {
            try {
                return JSON.stringify(obj, null, 2);
            } catch {
                return "[Unserializable Data]";
            }
        },
    },
    mounted() {
        this.fetchJobs();
    },
};
</script>
<style scoped>
pre {
    white-space: pre-wrap;
    word-break: break-word;
    overflow-x: auto;
    border-left: 4px solid #ddd;
}

.job-popup-container {
    position: fixed;
    top: 1rem;
    right: 1rem;
    z-index: 1000;
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.job-popup {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* Fade animation */
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}
</style>