<script setup>
import { getAssetSubList, deleteAssetSubItem } from "@/apis/asset";
import { ref, onMounted, watch, inject } from "vue";
import useSearchParam from "@/hooks/useSearchParam";
import useActiveBtn from "@/hooks/useActiveBtn";
import AssetSubListAddModal from "./AssetSubListAddModal.vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { searchParams, changeParams } = useSearchParam();
const { items, changeActiveBtn, setItems, selectedBtn } = useActiveBtn();
const { openToast, cancelToastOpen } = inject("app_toast");
const isEditMode = ref(false);
const getSubSystems = async (id) => {
  const res = await getAssetSubList(id);
  const sub = res.data.map((d, index) => ({
    ...d,
    title: d.system_key,
    key: d.id,
    active: searchParams.value?.subSys_id
      ? parseInt(searchParams.value?.subSys_id) === d.id
      : index === 0,
  }));
  setItems(sub);
};

onMounted(() => {});

watch(selectedBtn, (newValue) => {
  if (newValue && newValue.key) {
    changeParams({
      ...searchParams.value,
      subSys_id: newValue.key,
    });
  }
});

watch(
  () => searchParams,
  (newValue) => {
    if (newValue.value.mainSys_id && !newValue.value.subSys_id) {
      getSubSystems(parseInt(newValue.value.mainSys_id));
    }
  },
  {
    deep: true,
  }
);
const formState = ref({
  id: 0,
  system_key: "",
  system_value: "",
  system_parent_id: 0,
  file: [],
  device_image: "",
});



const openModal = (item) => {
  if (item.id) {
    formState.value = { ...item };

    if (item.device_image) {
      const subFile = item
        ? {
            name: item.device_image,
            src: item.device_image,
            ext: item.device_image?.split(".")[1],
          }
        : {};
      formState.value.file = [subFile];
      formState.value.device_image = item.device_image;
    }
  } else {
    formState.value = {
      id: 0,
      system_key: "",
      system_value: "",
      system_parent_id: 0,
      file: [],
      device_image: "",
    };
  }
  asset_add_sub_item.showModal();
};

const deleteItem = async (id) => {
  openToast("warning", t("msg.sure_to_delete"), "body", async () => {
    await cancelToastOpen();
    const res = await deleteAssetSubItem(id);
    if (res.isSuccess) {
      openToast("success", t("msg.delete_success"));
      getSubSystems(parseInt(searchParams.value.mainSys_id));
    } else {
      openToast("error", res.msg);
    }
  });
};
</script>

<template>
  <div class="mt-4">
    <div class="flex flex-wrap items-center gap-4 mb-4">
      <h2 class="text-lg font-bold ps-2 whitespace-nowrap">
        {{ $t("history.device_category") }} :
      </h2>
      <AssetSubListAddModal
        :openModal="openModal"
        :getData="getSubSystems"
        :formState="formState"
      />
      <button
        @click.stop.prevent="isEditMode = !isEditMode"
        class="btn btn-sm btn-outline-success mr-3"
      >
        {{ isEditMode ? t("button.stop_edit") : t("button.start_edit") }}
      </button>
    </div>
    <ButtonConnectedGroup
      :items="items"
      :onclick="
        (e, item) => {
          if (!isEditMode) {
            changeActiveBtn(item);
          }
        }
      "
      :className="`flex flex-wrap w-full mt-2`"
      size="sm"
      color="info"
    >
      <template #buttonContent="{ item }">
        <span class="text-base">{{ item.title }}</span>
        <template v-if="isEditMode">
          <span
            class="ml-2 text-base text-warning"
            @click.stop.prevent="() => openModal(item)"
          >
            <FontAwesomeIcon :icon="['fas', 'pencil-alt']"></FontAwesomeIcon>
          </span>
          <span
            class="text-base mx-1 text-error"
            @click.stop.prevent="() => deleteItem(item.id)"
          >
            <FontAwesomeIcon :icon="['fas', 'trash-alt']" />
          </span>
        </template>
      </template>
    </ButtonConnectedGroup>
  </div>
</template>

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