<script setup>
import { ref, onMounted, watch } from "vue";
import useSearchParam from "@/hooks/useSearchParam";
import useActiveBtn from "@/hooks/useActiveBtn";
import useBuildingStore from "@/stores/useBuildingStore";

const { searchParams, changeParams } = useSearchParam();
const { items, changeActiveBtn, setItems, selectedBtn } = useActiveBtn();
const store = useBuildingStore();

const updateSubSystemsFromStore = () => {
  const subSystems = store.subSys
    .filter(subSystem => subSystem.is_alarm === 1)
    .map(subSystem => ({
      title: subSystem.full_name,
      key: subSystem.sub_system_tag,
      active: searchParams.value?.subSys_id
        ? searchParams.value.subSys_id === subSystem.sub_system_tag
        : subSystem.sub_system_tag == "DP",
    }));
  setItems(subSystems);
};

onMounted(() => {
  updateSubSystemsFromStore();
});

watch(() => store.subSys, () => {
  updateSubSystemsFromStore();
}, { deep: true });

watch(selectedBtn,
  (newValue) => {
    if (newValue) {
      changeParams({ subSys_id: newValue.key });
    }
  }
);
</script>

<template>
  <div class="mt-4">
    <span v-if="!items.length" className="loading loading-spinner loading-lg text-info"></span>
    <ButtonConnectedGroup v-else :items="items" 
      :onclick="(e, item) => {changeActiveBtn(item)}"
      :className="`flex w-full mt-4`" size="sm" color="info">
      <template #buttonContent="{ item }">
        <span class="text-base">{{ item.title }}</span>
      </template>
    </ButtonConnectedGroup>
  </div>
</template>

<style lang="scss" scoped></style>