<script setup>
import {
  getHistoryFavorite,
  deleteHistoryFavorite,
  addHistoryFavorite,
  editHistoryFavorite,
} from "@/apis/history";
import { ref, onMounted, onUnmounted } from "vue";
import useSearchParam from "@/hooks/useSearchParam";
import { twMerge } from "tailwind-merge";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { searchParams, changeParams } = useSearchParam();

const items = ref([]);
const dropdownIsOpen = ref(false);
const loading = ref("");

const changeLoading = (value) => {
  loading.value = value;
};

const openDropdown = () => {
  dropdownIsOpen.value = true;
};

const closeDropdown = () => {
  dropdownIsOpen.value = false;
};

const getItems = async () => {
  const res = await getHistoryFavorite();
  items.value = res.data.map((d) => ({ ...d, key: d.favorite_guid }));
};

const removeItem = async (guid) => {
  const res = await deleteHistoryFavorite(guid);
  getItems();
};
const editKey = ref("");
const editName = ref("");

const clearInput = () => {
  editKey.value = "";
  editName.value = "";
};
const editItem = (guid, name) => {
  editKey.value = guid;
  editName.value = name;
};

const confirmEdit = async () => {
  changeLoading(editKey.value);
  const res = await editHistoryFavorite({
    favorite_guid: editKey.value,
    favorite_name: editName.value,
  });
  getItems();
  clearInput();
  changeLoading("");
};

const isAdding = ref(false);
const addItem = async (status) => {
  isAdding.value = status;
  if (!status) {
    isAdding.value = false;
    changeLoading("Adding");
    const res = await addHistoryFavorite({
      ...searchParams.value,
      favorite_name: editName.value,
    });
    getItems();
    changeLoading("");
  } else {
    clearInput();
  }
};

const cancelEditing = () => {
  isAdding.value = false;
  clearInput();
  closeDropdown();
};

const changeToFavorite = (data) => {
  changeParams({
    Type: data.type,
    points: data.points,
    Device_list: data.device_list,
    sub_system_tag: data.device_name_tag,
  });
};

onMounted(() => {
  getItems();
  document.querySelector("body").addEventListener("click", cancelEditing);
});

onUnmounted(() => {
  document.querySelector("body").removeEventListener("click", cancelEditing);
});
</script>

<template>
  <Dropdown :items="items" :open="dropdownIsOpen">
    <template #dropdownButton>
      <button
        class="btn btn-outline-success"
        @click.stop.prevent="openDropdown"
      >
        {{ $t("history.combinations") }}
      </button>
    </template>
    <template #dropdownItem="{ record }">
      <div class="py-0 flex items-center justify-between min-w-[320px]">
        <template v-if="editKey !== record.favorite_guid">
          <p
            class="py-3 pr-8 text-start cursor-pointer"
            @click.stop="() => changeToFavorite(record)"
          >
            {{ record.favorite_name }}
          </p>
          <p>
            <font-awesome-icon
              :icon="['fas', 'pencil-alt']"
              class="mr-4 hover:text-success"
              @click.stop.prevent="
                () => editItem(record.favorite_guid, record.favorite_name)
              "
            />
            <font-awesome-icon
              :icon="['fas', 'trash-alt']"
              class="hover:text-error"
              @click.stop.prevent="
                () => {
                  removeItem(record.favorite_guid);
                }
              "
            />
          </p>
        </template>
        <template v-else>
          <input
            v-focus
            v-model="editName"
            type="text"
            class="px-2 py-2 bg-transparent rounded-md mr-3"
            @click.stop.prevent
          />
          <button class="btn btn-info mr-2" @click.stop.prevent="confirmEdit">
            <p
              v-if="loading === record.favorite_guid"
              class="loading loading-spinner text-secondary"
            ></p>
            <span v-else>{{ $t("button.add") }}</span>
          </button>
          <button
            class="btn btn-error text-white"
            @click.stop.prevent="clearInput"
          >
            {{ $t("button.cancel") }}
          </button>
        </template>
      </div>
    </template>
    <template #dropdownAction>
      <li class="mt-3 w-full flex justify-between">
        <input
          v-if="isAdding"
          v-focus
          v-model="editName"
          type="text"
          :placeholder="t('button.enter_text')"
          class="p-3 mr-2 bg-transparent rounded-md"
          @click.stop.prevent
        />
        <button
          :class="twMerge('btn  btn-info mr-2', isAdding ? '' : 'w-full')"
          @click.stop.prevent="() => addItem(!isAdding)"
        >
          <span
            v-if="loading === 'Adding'"
            class="loading loading-spinner text-secondary"
          ></span>
          <span v-else>{{ $t("button.add") }}</span>
        </button>
        <button
          v-if="isAdding"
          class="btn btn-error text-white"
          @click.stop.prevent="
            () => {
              clearInput();
              isAdding = false;
            }
          "
        >
          {{ $t("button.cancel") }}
        </button>
      </li>
    </template>
  </Dropdown>
</template>

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