<template>
  <section class="min-h-[600px] h-screen">
    <h1 class="text-2xl font-extrabold mb-2">{{ $t("rtsp.title") }}</h1>

    <!-- Tabs：選擇攝影機 -->
    <div class="flex items-center gap-4 mb-6">
      <h2 class="text-lg font-bold whitespace-nowrap">
        {{ $t("rtsp.selectDevice") }} :
      </h2>

      <ButtonConnectedGroup
        :items="items"
        :onclick="
          (e, item) => {
            changeActiveBtn(item);
            const found = rtspDevices.find((r) => r.main_id === item.key);
            if (found) selectDevice(found);
          }
        "
        :className="`flex flex-wrap`"
        size="sm"
        color="info"
      >
        <template #buttonContent="{ item }">
          <span class="text-base">{{ item.title }}</span>
        </template>
      </ButtonConnectedGroup>
    </div>

    <div class="flex h-[70%] gap-4">
      <!-- 左側：即時監控 -->
      <div class="relative w-full flex-1 rounded border overflow-hidden">
        <iframe
          :src="monitorUrl"
          class="absolute inset-0 w-full h-full"
          allow="autoplay; fullscreen; picture-in-picture"
          referrerpolicy="no-referrer"
        ></iframe>
      </div>

      <!-- 右側：開始/結束偵測 -->
      <aside class="w-1/2 flex flex-col gap-6 p-4">
        <div class="flex gap-3">
          <button
            class="btn btn-add w-40"
            @click="startDetection"
            :disabled="
              isStarting || !selectedMainId || !currentDevice?.start_btn_enable
            "
            :title="!selectedMainId ? $t('rtsp.pleaseSelectDevice') : ''"
          >
            {{ $t("rtsp.start") }}
          </button>

          <button
            class="btn btn-error text-white w-40"
            @click="stopDetection"
            :disabled="
              isStopping || !selectedMainId || !currentDevice?.stop_btn_enable
            "
            :title="!selectedMainId ? $t('rtsp.pleaseSelectDevice') : ''"
          >
            {{ $t("rtsp.stop") }}
          </button>
        </div>

        <!-- 顯示後端傳來的提示文字 -->
        <p v-if="currentDevice?.alarm_message" class="text-sm text-info">
          {{ currentDevice.alarm_message }}
        </p>

        <p v-if="message" class="text-sm">{{ message }}</p>
      </aside>
    </div>
  </section>
</template>

<script>
import { getRtspDevices, setRtspEnable } from "@/apis/rtsp";
import useActiveBtn from "@/hooks/useActiveBtn";

const DEFAULT_MONITOR_URL =
  "http://192.168.0.219:8026/?url=rtsp://admin02:mjmAdmin_99@192.168.0.200:554/stream1";

export default {
  name: "Rtsp",
  setup() {
    const { items, changeActiveBtn, setItems, selectedBtn } = useActiveBtn();
    return { items, changeActiveBtn, setItems, selectedBtn };
  },
  data() {
    return {
      monitorUrl: DEFAULT_MONITOR_URL,
      isStarting: false,
      isStopping: false,
      message: "",
      rtspDevices: [],
      selectedMainId: null, // 目前選中的設備 main_id
    };
  },
  computed: {
    currentDevice() {
      if (!this.selectedMainId) return null;
      return (
        this.rtspDevices.find((d) => d.main_id === this.selectedMainId) || null
      );
    },
  },
  async mounted() {
    await this.loadRtspDevices();
  },
  watch: {
    selectedBtn: {
      handler(newVal) {
        if (!newVal) return;
        const found = this.rtspDevices.find((r) => r.main_id === newVal.key);
        if (found) this.selectDevice(found);
      },
      deep: true,
    },
  },
  methods: {
    async loadRtspDevices() {
      try {
        const res = await getRtspDevices({});
        const list = Array.isArray(res) ? res : res?.data || [];

        this.rtspDevices = list;

        // 建立 Tabs
        const cate = this.rtspDevices.map((d, index) => ({
          title: d.full_name || d.main_id,
          key: d.main_id,
          active: this.selectedMainId
            ? this.selectedMainId === d.main_id
            : index === 0,
        }));
        this.setItems(cate);

        // 預設選第一台
        if (this.rtspDevices.length > 0) {
          const chosenId = this.selectedMainId ?? this.rtspDevices[0].main_id;
          const chosen =
            this.rtspDevices.find((d) => d.main_id === chosenId) ||
            this.rtspDevices[0];
          this.selectDevice(chosen);
        } else {
          this.selectedMainId = null;
          this.monitorUrl = DEFAULT_MONITOR_URL;
        }
      } catch (err) {
        console.error("loadRtspDevices() 失敗", err);
        this.rtspDevices = [];
        this.setItems([]);
        this.selectedMainId = null;
        this.monitorUrl = DEFAULT_MONITOR_URL;
      }
    },

    // 切換設備 Tab
    selectDevice(d) {
      this.selectedMainId = d.main_id;
      this.monitorUrl = d.rtsp_url || DEFAULT_MONITOR_URL;
    },

    // 開始偵測
    async startDetection() {
      if (!this.selectedMainId) {
        this.message = this.$t("rtsp.pleaseSelectDevice");
        return;
      }
      this.isStarting = true;
      const keepId = this.selectedMainId;
      try {
        await setRtspEnable({ main_id: keepId, enable: true });
        await this.loadRtspDevices();
        const found = this.rtspDevices.find((d) => d.main_id === keepId);
        if (found) this.selectDevice(found);
        this.message = this.$t("rtsp.startSuccess");
      } catch (e) {
        console.error(e);
        this.message = this.$t("rtsp.startFail");
      } finally {
        this.isStarting = false;
      }
    },

    // 結束偵測
    async stopDetection() {
      if (!this.selectedMainId) {
        this.message = this.$t("rtsp.pleaseSelectDevice");
        return;
      }
      this.isStopping = true;
      const keepId = this.selectedMainId;
      try {
        await setRtspEnable({ main_id: keepId, enable: false });
        await this.loadRtspDevices();
        const found = this.rtspDevices.find((d) => d.main_id === keepId);
        if (found) this.selectDevice(found);
        this.message = this.$t("rtsp.stopSuccess");
      } catch (e) {
        console.error(e);
        this.message = this.$t("rtsp.stopFail");
      } finally {
        this.isStopping = false;
      }
    },
  },
};
</script>
