<template>
    <div>
        <manage-sidebar />
        <div class="page-wrapper">
            <div class="page-header d-print-none">
                <div class="container-fluid">
                    <h2 class="page-title">Live Monitoring Project</h2>
                </div>
            </div>

            <div class="page-body">
                <div class="container-fluid">
                    <div class="card">
                        <div class="card-body">
                            <!-- Camera select -->
                            <div class="col-lg-4 mb-3">
                                <label>Select Camera</label>
                                <multiselect v-model="selectedCameraId"
                                    :options="cameras.map(c => ({ label: c.camera_name, value: c.id }))"
                                    placeholder="-- Search Camera --" label="label" track-by="value" />
                            </div>

                            <!-- Video -->
                            <div v-if="currentStream">
                                <div class="card shadow-sm mb-5">
                                    <div class="card-header bg-light">
                                        <strong>{{ currentStream.camera_name }}</strong>
                                    </div>
                                    <div class="card-body p-0">
                                        <video :key="`video-${currentStream.id}`" ref="videoPlayer"
                                            class="video-js vjs-default-skin vjs-big-play-centered" controls
                                            preload="auto" playsinline muted style="width: 100%; height: auto;"></video>
                                    </div>
                                </div>
                            </div>
                            <div v-else>
                                <p class="text-muted">⏳ Menunggu stream tersedia...</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <manage-footer />
        </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";
import Multiselect from "vue-multiselect";
import "vue-multiselect/dist/vue-multiselect.css";

import videojs from "video.js";
import "video.js/dist/video-js.css";

export default {
    name: "LiveMonitoringProject",
    components: { ManageSidebar, ManageFooter, Multiselect },
    data() {
        return {
            cameras: [],
            selectedCameraId: null,
            currentStream: null,
            player: null,
        };
    },
    computed: {
        ...mapGetters(["user", "authToken"]),
    },
    methods: {
        ...mapActions(["logout"]),

        async fetchCameras() {
            try {
                const res = await axios.get("/api/cctv-live-monitoring-project", {
                    headers: { Authorization: `Bearer ${this.authToken}` },
                    params: { itemsPerPage: 200 },
                });
                this.cameras = res.data.data || [];
            } catch (error) {
                console.error("Error fetching cameras:", error);
                this.showErrorAlert("Error fetching cameras.");
            }
        },

        async onCameraChange() {
            if (!this.selectedCameraId) {
                this.currentStream = null;
                return;
            }

            try {
                const res = await axios.get(
                    `/api/cctv-live-monitoring-project/${this.selectedCameraId.value}`,
                    { headers: { Authorization: `Bearer ${this.authToken}` } }
                );
                this.currentStream = res.data;

                // Tunggu DOM update
                await this.$nextTick();

                // ⚠️ Tambahkan jeda kecil agar ref benar-benar terupdate
                setTimeout(() => {
                    this.initPlayer(this.currentStream.url);
                }, 0);

            } catch (error) {
                console.error("Error fetching stream:", error);
                this.showErrorAlert("Error fetching CCTV stream.");
            }
        },

        initPlayer(streamUrl) {
            const videoElement = this.$refs.videoPlayer;

            if (!videoElement) {
                console.warn("Video element still not found after nextTick + timeout. Retrying once...");
                // Coba sekali lagi setelah 100ms
                setTimeout(() => {
                    const el = this.$refs.videoPlayer;
                    if (el) {
                        this.initPlayerAfterDelay(el, streamUrl);
                    } else {
                        console.error("Video element not found after retry.");
                    }
                }, 100);
                return;
            }

            this.initPlayerAfterDelay(videoElement, streamUrl);
        },

        initPlayerAfterDelay(videoElement, streamUrl) {
            // Hapus player lama
            if (this.player) {
                this.player.dispose();
            }

            // Inisialisasi player baru
            this.player = videojs(videoElement, {
                autoplay: true,
                controls: true,
                preload: "auto",
                fluid: true,
                sources: [
                    {
                        src: streamUrl,
                        type: "application/x-mpegURL",
                    },
                ],
            });

            // Handle error
            this.player.on("error", () => {
                const err = this.player.error();
                console.error("Video.js error:", err);

                if (err && err.code === 2) {
                    setTimeout(() => {
                        this.player.src({ src: streamUrl, type: "application/x-mpegURL" });
                        this.player.play();
                    }, 5000);
                }
            });
        },

        showErrorAlert(msg) {
            Swal.fire({
                icon: "error",
                title: msg,
                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.",
            }).then(() => this.logout());
        } else {
            this.fetchCameras();
        }
    },
    beforeUnmount() {
        if (this.player) {
            this.player.dispose();
        }
    },
    watch: {
        selectedCameraId(newVal) {
            if (newVal) {
                this.onCameraChange();
            } else {
                this.currentStream = null;
            }
        },
    },
};
</script>
