<script setup lang="ts">
// 1. Imports
// 2. Metas
// 3. Props
// 2. Reactive State
// 3. Computed Properties
// 4. Functions / Methods
// 5. Lifecycle Hooks
// 6. Watchers

// #region imports
import hadithaApi from "@haditha/apis/hadithaApi";
import type { HadithResponseModel } from "@haditha/types/hadithType";
import type { HadithResponseShowModel } from "~/systems/hadith_ui/types/hadithType";
import headLinks from "@haditha/json/haditha/headLinks";
import headMetas from "@haditha/json/haditha/headMetas";
// #endregion imports

// #region meta
definePageMeta({
  layout: false,
  name: "hadithaSearchShow",
});

const route = useRoute();
const router = useRouter();

useHead({
  title: `${import.meta.env.VITE_HADITH_PAGE_TITLE}`,
  meta: [
    { name: "description", content: "کاوش با هوش مصنوعی در احادیث اسلامی" },
    ...headMetas,
  ],
  bodyAttrs: {
    class: [import.meta.env.VITE_HADITH_SYSTEM, "search-show-page"],
  },
  link: headLinks,
});
// #endregion imports

// #region props
// const props = defineProps({
//   selectedItem: {
//     type: Object,
//     default() {
//       return {};
//     },
//   },
// });
// #endregion props

// #region refs and reactives
const emit = defineEmits(["close"]);
const loading = ref(false);
const httpService = useNuxtApp()["$http"];
const toast = useToast();

// #endregion refs and reactives

// #region methods
const fetchData = () => {
  let url = hadithaApi.search.show;
  url = url.replace("@index_key", "dhparag");
  url = url.replace("@id", route.params.id);

  return httpService.getRequest(url);
};

const { data: selectedItem } = useAsyncData("parags", () => fetchData());

const hadithAddress = computed(() => {
  return `${selectedItem.value?._source?.address?.vol_title}، صفحه
   ${selectedItem.value?._source?.address?.page_num}`;
});

const goToTheSearch = (type: string) => {
  router.push({
    name: "hadithaSearch",
    query: {
      q: route.query.q ?? "",
    },
  });
};
const goToTheChatbot = () => {
  router.push({
    name: "hadithaChatBot",
  });
};

const handleFavorite = async () => {
  if (selectedItem.value?._source?.tbookmark) {
    await removeFromFavorites(selectedItem.value);
    selectedItem.value._source.tbookmark = false;
  } else {
    await addToFavorites(selectedItem.value);
    selectedItem.value._source.tbookmark = true;
  }
};

const addToFavorites = async (item = {}) => {
  let url = repoUrl() + hadithaApi.favorite.add;
  url = url.replace("{{data_type}}", "bookmark");
  url = url.replace("{{ref_key}}", "dhparag");
  const formData = {
    ref_id: item._id,
    title: item._source.content,
  };
  httpService
    .postRequest(url, formData)
    .then((res) => {
      toast.add({
        title: "انجام شد.",
        description: "به نشان شده ها افزوده شد",
        color: "success",
      });
    })
    .catch((err) => {
      toast.add({
        title: "خطا",
        description: "خطایی رخ داد.لطفا دوباره امتحان کنید.",
        color: "error",
      });
    });
};

const removeFromFavorites = async (item = {}, index = 0) => {
  let url = repoUrl() + hadithaApi.favorite.deleteByRefid;
  url = url.replace("{{data_type}}", "bookmark");
  url = url.replace("{{index_key}}", "dhparag");
  url = url.replace("{{ref_id}}", item._id);

  const formData = {
    ref_id: item._id,
    title: item._source.title,
  };
  httpService
    .postRequest(url, formData)
    .then((res) => {
      toast.add({
        title: "انجام شد.",
        description: "به نشان شده ها افزوده شد",
        color: "success",
      });
    })
    .catch((err) => {
      toast.add({
        title: "خطا",
        description: "خطایی رخ داد.لطفا دوباره امتحان کنید.",
        color: "error",
      });
    });
};

const handlePagination = (prevNextIndicator: string) => {
  if (loading.value) return;
  loading.value = true;

  let url = repoUrl() + hadithaApi.search.prevNextHadith;
  url = url.replace("@index_key", "dhparag");
  url = url.replace("@vol_id", selectedItem.value?._source?.address?.vol_id);
  url = url.replace("@parag_order", selectedItem.value?._source?.parag_order);
  url = url.replace("@step", prevNextIndicator);

  httpService
    .getRequest(url)
    .then((res) => {
      selectedItem.value = res.hits.hits?.[0];
    })
    .finally(() => (loading.value = false));
};

const onKeyWordClick = (keyword) => {
  router.push({
    name: "hadithaSearch",
    query: {
      q: route.query.q ?? "",
      f_aik: keyword ?? "",
    },
  });
};
const onClassClick = (aiclass) => {
  router.push({
    name: "hadithaSearch",
    query: {
      q: route.query.q ?? "",
      f_aik: aiclass ?? "",
    },
  });
};
// const localCopyTextToClipboard = (text: string) => {
//   copyTextToClipboard(text);
// };
// #endregion methods

const showArabicText = computed(() => {
  return selectedItem.value?._source?.content_ar?.length;
});
const showPersianText = computed(() => {
  return selectedItem.value?._source?.content?.length;
});
const showDescriptionText = computed(() => {
  return selectedItem.value?._source?.description?.length;
});
const showKewrodAndClassesText = computed(() => {
  return (
    selectedItem.value?._source?.ai_keywords?.length ||
    selectedItem.value?._source?.ai_classes?.length
  );
});

// #region hooks
// onMounted(() => {
//   console.info("mounted");
// });
// #endregion methods
// components declaration
const HadithaLayout = defineAsyncComponent(
  () => import("@haditha/layouts/HadithaLayout.vue")
);
const NavigationMenu = defineAsyncComponent(
  () => import("@haditha/components/haditha/NavigationMenu.vue")
);
</script>

<template>
  <HadithaLayout>
    <div class="page-container h-full">
      <div class="page-header">
        <UContainer
          ui="{
          base: 'sm:px-6 lg:px-4',
        }"
          class="max-w-[var(--ui-container-two)] sm:px-6 lg:px-4"
        >
          <navigation-menu class="static py-4"></navigation-menu>
        </UContainer>
      </div>
      <UContainer
        ui="{
          base: 'sm:px-6 lg:px-4',
        }"
        class="page-inner-container search sm:px-6 lg:px-0 mt-6"
      >
        <div class="search-show-page lg:px-12 py-4">
          <div class="body-header pb-6 flex justify-between">
            <div class="flex justify-between pagination flex-1 items-center">
              <UButton
                @click="handlePagination('-1')"
                class="prev-haditha"
                label="حدیث قبل"
                color=""
                variant="soft"
                icon="i-haditha-chevron-right"
              />
              <UButton
                @click="handlePagination('1')"
                class="next-haditha"
                label="حدیث بعد"
                color=""
                variant="soft"
                trailing-icon="i-haditha-chevron-left"
              />
            </div>

            <div class="flex justify-between actions mr-8">
              <UButton
                disabled
                class="similar-btn"
                icon="i-haditha-search-3"
                label="مشابه"
                color="neutral"
                variant="outline"
                @click.prevent="goToTheSearch('similar')"
              />
              <UButton
                class="explore-btn mr-8"
                trailing-icon="i-haditha-explore"
                label="کاوش"
                variant="solid"
                @click.prevent="goToTheChatbot"
              />
            </div>
            <!-- <div>
              <span class="top-left-bgi z-0"></span>
              <div class="modal-title flex justify-between">
                <ULink
                  raw
                  :to="{ name: 'haditha' }"
                  class="flex justify-center items-center me-3"
                >
                  <img
                    fit="auto"
                    quality="80"
                    src="/img/haditha/haditha-title.svg"
                  />
                </ULink>

                <UButton
                  icon="i-haditha-close"
                  color="neutral"
                  variant="ghost"
                  class="close-btn text-[var(--ui-color-two)] hover:bg-gray-300"
                  @click="goToTheSearch('normal')"
                />
              </div>
            </div> -->
          </div>

          <div class="body-content">
            <div class="h-full flex flex-col justify-center z-2">
              <div class="bg-container">
                <div class="header flex">
                  <UButton
                    @click="handleFavorite"
                    :variant="
                      selectedItem?._source?.tbookmark ? 'soft' : 'ghost'
                    "
                    color="primary"
                    class="bookmark-btn"
                    :icon="
                      selectedItem?._source?.tbookmark
                        ? 'i-haditha-tag-active'
                        : 'i-haditha-tag'
                    "
                  >
                  </UButton>

                  <ULink
                    :to="{
                      name: 'hadithaLibraryShow',
                      params: {
                        id: selectedItem?._source?.address.vol_id,
                        slug: hadithAddress,
                      },
                      query: {
                        page_num: selectedItem?._source?.address?.page_num,
                      },
                    }"
                    color="neutral"
                    variant="ghost"
                    :ui="{
                      leadingIcon: 'text-(--ui-primary)',
                    }"
                    class="referene bg-white hover:bg-gray-100"
                  >
                    <span> نشانی: </span>
                    {{ hadithAddress ?? "" }}
                  </ULink>
                </div>

                <div class="content firefox-scrollbar">
                  <div class="search-item">
                    <template v-if="showArabicText">
                      <div class="text-arabic-section">
                        <div class="section-header">
                          <span class="section-title">
                            {{
                              selectedItem?._source?.meta?.hadith_masoum ??
                              selectedItem?._source?.meta?.hadith_sanad
                            }}
                          </span>

                          <UButton
                            v-if="
                              selectedItem?._source?.meta?.hadith_masoum
                                ?.length ||
                              selectedItem?._source?.meta?.hadith_sanad
                            "
                            @click="
                              copyTextToClipboard(
                                selectedItem?._source?.content_ar ?? ''
                              )
                            "
                            variant="ghost"
                            class="copy-btn"
                            label="کپی"
                          />
                        </div>
                        <div
                          v-if="selectedItem?._source?.content_ar?.length"
                          class="arabic-text"
                        >
                          <p>
                            {{ selectedItem?._source?.content_ar ?? "" }}
                          </p>
                        </div>
                      </div>

                      <div class="separator"></div>
                    </template>
                    <template v-if="showPersianText">
                      <div class="text-persian-section">
                        <div class="section-header">
                          <span class="section-title"> ترجمه </span>
                          <UButton
                            @click="
                              copyTextToClipboard(
                                selectedItem?._source?.content
                              )
                            "
                            variant="ghost"
                            class="copy-btn"
                            label="کپی"
                          />
                        </div>

                        <p
                          class="from"
                          v-if="
                            selectedItem?._source?.meta?.hadith_masoum ||
                            selectedItem?._source?.meta?.hadith_sanad
                          "
                        >
                          {{
                            selectedItem?._source?.meta?.hadith_masoum ??
                            selectedItem?._source?.meta?.hadith_sanad
                          }}:
                        </p>
                        <p
                          class="persian-text"
                          v-html="selectedItem?._source?.content"
                        ></p>
                      </div>

                      <div class="separator"></div>
                    </template>

                    <template v-if="showDescriptionText">
                      <div
                        v-if="selectedItem?._source?.description?.length"
                        class="text-description-section"
                      >
                        <div class="section-header">
                          <span class="section-title"> شرح </span>
                          <UButton
                            @click="
                              copyTextToClipboard(
                                selectedItem?._source?.description
                              )
                            "
                            variant="ghost"
                            class="copy-btn"
                            label="کپی"
                          />
                        </div>
                        <p
                          class="description-item"
                          v-html="selectedItem?._source?.description"
                        ></p>
                      </div>

                      <div class="separator"></div>
                    </template>

                    <template v-if="showKewrodAndClassesText">
                      <div class="text-description-section">
                        <div
                          v-if="selectedItem?._source?.ai_keywords?.length"
                          class="mb-4"
                        >
                          <span class="text-sm"> کلیدواژگان: </span>
                          <UButton
                            class="me-1 text-sm"
                            v-for="(keyword, i) in selectedItem?._source
                              ?.ai_keywords"
                            :key="i"
                            @click.prevent="onKeyWordClick(keyword)"
                            variant="soft"
                          >
                            <!-- {{ i > 0 ? "," : "" }} -->
                            {{ keyword }}
                          </UButton>
                        </div>

                        <div v-if="selectedItem?._source?.ai_classes?.length">
                          <span class="text-sm"> دسته بندی ها: </span>
                          <UButton
                            class="me-1 text-sm"
                            v-for="(aiClass, i) in selectedItem?._source
                              ?.ai_classes"
                            :key="i"
                            @click.prevent="onClassClick(aiClass)"
                            variant="soft"
                          >
                            <!-- {{ i > 0 ? "," : "" }} -->
                            {{ aiClass.label }}
                          </UButton>
                        </div>
                      </div>
                    </template>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- <div class="body-footer"> -->
          <!-- <div class="mt-5 pb-5 z-2"> -->
          <!-- <div class="flex justify-between actions">
            <UButton
              disabled
              class="similar-btn"
              icon="i-haditha-search-3"
              label="مشابه"
              color="neutral"
              variant="outline"
              @click.prevent="goToTheSearch('similar')"
            />
            <UButton
              class="explore-btn"
              trailing-icon="i-haditha-explore"
              label="کاوش"
              variant="solid"
              @click.prevent="goToTheChatbot"
            />
          </div> -->
          <!-- </div> -->
          <!-- </div> -->
        </div>
      </UContainer>
    </div>
  </HadithaLayout>
</template>

<!-- because of the buttons, using without scoped. -->
<style>
body.hadith-system.search-show-page {
  /* background-color: #f7fffd; */
}

body.hadith-system.search-show-page {
  .page-header {
    width: 1920;
    height: 100;
    /* gap: 24px; */
    border-bottom: 0.5px solid #76ffda;

    /* padding-top: 8px; */
    /* padding-right: 24px; */
    /* padding-bottom: 24px; */
    /* padding-left: 24px; */

    background-image: url("/img/haditha/search-show-header.png");
    background-repeat: no-repeat;
    background-size: cover;
  }
}
.page-inner-container {
  /* height: 100%; */
  max-width: 1200px;
  width: 100%;

  &.search {
    box-shadow: 0px 8px 20px 0px #0000001a;
    border: 0.3px solid #e0e0e0;
    /* width: 1200; */
    /* height: 1028; */
    gap: 8px;
    border-radius: 16px;
  }
}
.search-show-page {
  .body-header {
    /* padding-top: 5em; */

    .actions {
      /* margin-bottom: 1em; */

      .similar-btn {
        width: 114;
        height: 56;
        gap: 8px;
        border-radius: 12px;
        /* border-width: 0.5px; */
        padding-top: 8px;
        padding-right: 20px;
        padding-bottom: 8px;
        padding-left: 24px;
        /* background: #ffffff; */
        /* border: 0.5px solid; */

        /* border-image-source: linear-gradient(
          102.02deg,
          #4be8ae 7.38%,
          #00a762 91.78%
        ); */
        /* box-shadow: 0px 8px 20px 0px #0000001a; */

        font-family: var(--font);
        font-weight: 400;
        font-size: 15px;
        line-height: 22.5px;
        letter-spacing: 0%;
        text-align: right;
        color: var(--ui-color-two);
      }
      .explore-btn {
        width: 118;
        height: 56;
        gap: 4px;
        border-radius: 12px;
        padding-top: 8px;
        padding-right: 24px;
        padding-bottom: 8px;
        padding-left: 20px;
        background: linear-gradient(268.94deg, #d284ff -0.65%, #4d00ff 104.59%);
        /* box-shadow: 0px 8px 20px 0px #0000001a; */

        font-family: var(--font);
        font-weight: 400;
        font-size: 16px;
        line-height: 24px;
        letter-spacing: 0%;
        text-align: right;
        color: #fff;
      }
    }
    .pagination {
      padding: 0.7em 0px;

      /* width: 672; */
      /* height: 56; */
      justify-content: space-between;
      border-radius: 16px;
      /* border-width: 0.3px; */
      padding-right: 32px;
      padding-left: 32px;
      background: #ffffff;
      border: 0.3px solid #e0e0e0;
      /* box-shadow: 0px 8px 20px 0px #0000001a; */

      .prev-haditha {
        font-family: var(--font);
        font-weight: 300;
        font-size: 12px;
        line-height: 20px;
        letter-spacing: 0%;
        text-align: right;
        color: var(--ui-color-two);
      }
      .next-haditha {
        font-family: var(--font);
        font-weight: 300;
        font-size: 12px;
        line-height: 20px;
        letter-spacing: 0%;
        text-align: right;
        color: var(--ui-color-two);
      }

      .prev-haditha,
      .next-haditha {
        &:hover {
          cursor: pointer;
          background-color: #eee;
        }
      }
    }

    .modal-title {
      /* padding: 0 0.5em 1.5em; */
      /* margin-bottom: 2.5em; */

      .close-btn {
        /* color: var(--ui-color-two); */

        /* width: 24px; */
        /* height: 24px; */
        padding: 0.2em;
        /* background-color: transparent; */
      }
    }
  }
  .body-content {
    .header {
      .bookmark-btn {
        width: 49px;
        height: 32px;
        gap: 4px;
        border-radius: 6px;
        border-width: 0.5px;
        padding-top: 4px;
        padding-right: 12px;
        padding-bottom: 4px;
        padding-left: 12px;
        border: 0.5px solid #d9d9d9;
        /* background: #ffffff;  */
        display: flex;
        justify-content: center;
        align-items: center;

        /* span { */
        /* width: 19; */
        /* height: 21; */
        /* background: #29d985; */
        /* } */
      }

      .referene {
        margin-right: 0.5em;
        width: 182;
        height: 32;
        gap: 4px;
        border-radius: 6px;
        border-width: 0.5px;
        padding-top: 4px;
        padding-right: 12px;
        padding-bottom: 4px;
        padding-left: 12px;
        /* background-color: #ffffff; */
        border: 0.5px solid #d9d9d9;

        font-family: var(--font);
        font-weight: 300;
        font-size: 12px;
        line-height: 18px;
        letter-spacing: 0%;
        text-align: right;
        color: #8a92a8;
        display: flex;
        align-items: center;

        span {
          margin-left: 0.1em;
          font-family: var(--font);
          font-weight: 300;
          font-size: 12px;
          line-height: 18px;
          letter-spacing: 0%;
          text-align: right;
          color: #4d00ff;
        }
      }
    }
    .content {
      /* height: calc(100dvh - 15em); */
      /* overflow-y: auto; */
      /* padding-bottom: 5em; */

      .search-item {
        padding: 1em 0 1em 1em;

        .section-header {
          display: flex;
          justify-content: space-between;

          text-align: right;
          margin-bottom: 0.5em;

          .section-title {
            font-family: var(--font);
            font-weight: 400;
            font-size: 14px;
            line-height: 21px;
            letter-spacing: 0%;
            text-align: right;

            /* Fallback color */
            color: #4be8ae;

            /* Gradient background */
            background-image: linear-gradient(
              102.02deg,
              #4be8ae 7.38%,
              #00a762 91.78%
            );

            /* Clip the background to the text */
            background-clip: text;
            -webkit-background-clip: text; /* For Safari */

            /* Make the text transparent */
            color: transparent;
            -webkit-text-fill-color: transparent; /* For Safari */
          }

          .copy-btn {
            padding: 0.2em 1em;

            /* width: 44px; */
            /* height: 24px; */
            gap: 4px;
            border-radius: 6px;
            /* border-width: 0.5px; */
            padding-top: 4px;
            padding-right: 12px;
            padding-bottom: 4px;
            padding-left: 12px;
            /* background: #ffffff; */
            border: 0.5px solid #d9d9d9;

            font-family: var(--font);
            font-weight: 300;
            font-size: 12px;
            line-height: 18px;
            letter-spacing: 0%;
            text-align: right;

            color: #8a92a8;
          }
        }
        .text-arabic-section {
          padding: 2em 0;

          .arabic-text {
            font-family: var(--ar-font);
            font-weight: 400;
            font-size: 18px;
            line-height: 32px;
            letter-spacing: 0%;
            text-align: right;
            color: var(--ui-color-two);

            margin-bottom: 0.5em;
          }
        }

        .text-persian-section {
          padding: 2em 0;

          .section-header {
          }

          .from,
          .persian-text {
            /* font-family: Takrim; */
            font-family: var(--font);
            font-weight: 400;
            /* font-size: 18px; */
            font-size: 0.85rem;
            line-height: 30px;
            letter-spacing: 0%;
            text-align: right;
            color: var(--ui-color-two);
          }
          /* .persian-text {
        font-family: var(--ar-font);
            font-weight: 400;
            font-size: 16px;
            line-height: 22px;
            letter-spacing: 0%;
            text-align: right;
            color: #626b84;
            margin-bottom: 0.5em;
          } */
        }
        .text-description-section {
          padding: 2em 0;

          .description-item {
            font-family: var(--font);
            font-weight: 400;
            /* font-size: 18px; */
            font-size: 0.85rem;

            line-height: 30px;
            letter-spacing: 0%;
            text-align: right;
            color: var(--ui-color-two);

            /*             
            height: 24px;
            gap: 4px;
            padding-top: 4px;
            padding-right: 8px;
            padding-bottom: 4px;
            padding-left: 8px;
            border-radius: 6px;
            border-width: 0.5px;
            border: 0.5px solid #d9d9d9;

            font-family: var(--font);
            font-weight: 300;
            font-size: 10px;
            line-height: 15px;
            letter-spacing: 0%;
            text-align: right;
            color: #8a92a8; */
          }
        }

        .separator {
          /* border: 0.5px solid #eee; */
          height: 1px;
          background-position: center center;
          background-size: contain;

          background-image: linear-gradient(
            90deg,
            #ffffff 0%,
            #a0f5ff 30.4%,
            #3fc9fa 71.47%,
            #a7ffe7 100%
          );
        }
      }
    }
  }
  /* .body-footer {
    position: fixed;
    bottom: 0em;
    left: 0;
    right: 0;
    max-width: 1200px;
    margin: auto;

  
  } */
}
/* @media screen and (max-width: 719.99px) { */
/* .search-show-page { */
/* .body-content { */
/* .content { */
/* height: calc(100dvh - 15em); */
/* overflow-y: auto; */
/* } */
/* } */
/* } */
/* } */
</style>
