<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,
      sub_system_tag: [],
    });
  } else {
    changeParams({
      ...searchParams.value,
      sub_system_tag: store.subSys.map(({ sub_system_tag }) => sub_system_tag),
    });
  }
};

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

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

watch(searchParams, (newValue, oldValue) => {
  if (
    (!oldValue.work_type || oldValue.work_type == "3") &&
    !newValue.sub_system_tag
  ) {
    changeParams({
      ...newValue,
      sub_system_tag: [store.subSys[0]?.sub_system_tag],
    });
  }
});
</script>

<template>
  <div class="flex flex-wrap mt-3">
    <button
      class="btn 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>
