<script setup>
import useBuildingStore from "@/stores/useBuildingStore";
import Checkbox from "@/components/customUI/Checkbox.vue";
import { computed, onMounted, ref, watch } from "vue";
import useSearchParam from "@/hooks/useSearchParam";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { searchParams, changeParams } = useSearchParam();

const store = useBuildingStore();
const changeCheckedItem = () => {
  if (checkedItem.value.length === store.subSys.length) {
    changeParams({
      ...searchParams.value,
      device_name_tag: [],
    });
  } else {
    changeParams({
      ...searchParams.value,
      device_name_tag: store.subSys.map(({ sub_system_tag }) => sub_system_tag),
    });
  }
};

const onChange = (value, checked) => {
  if (checked) {
    changeParams({
      ...searchParams.value,
      device_name_tag: searchParams.value.device_name_tag
        ? typeof searchParams.value.device_name_tag === "string"
          ? [searchParams.value.device_name_tag, value]
          : [...searchParams.value.device_name_tag, value]
        : [value],
    });
  } else {
    changeParams({
      ...searchParams.value,
      device_name_tag: searchParams.value.device_name_tag.filter(
        (sub) => sub !== value
      ),
    });
  }
};

const checkedItem = computed(() =>
  searchParams.value.device_name_tag
    ? typeof searchParams.value.device_name_tag === "string"
      ? [searchParams.value.device_name_tag]
      : searchParams.value.device_name_tag
    : []
);

watch(searchParams, (newValue) => {
  if (!newValue.device_name_tag) {
    changeParams({
      ...newValue,
      device_name_tag: [store.subSys[0]?.sub_system_tag],
    });
  }
});
</script>

<template>
  <div class="flex flex-wrap mt-3">
    <h2 class="text-lg font-bold ps-1 pe-4">
        {{ $t("history.device_category") }} :
    </h2>
    <button
      class="btn btn-sm btn-success mr-4"
      @click.stop.prevent="changeCheckedItem"
    >
      {{ checkedItem.length === store.subSys.length ? t("button.deselect_all") : t("button.select_all") }}
    </button>
    <Checkbox
      v-for="sub in store.subSys"
      :key="sub.key"
      :title="sub.full_name"
      :value="sub.sub_system_tag"
      :checked="checkedItem.includes(sub.sub_system_tag)"
      class="mx-3 my-3 xl:my-0 text-lg"
      :onChange="onChange"
    />
  </div>
</template>

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