// src/views/info-dissemination/PublicationsView.vue
<template>
  <div class="container mx-auto px-4 py-8">
    <h1 class="text-3xl font-bold text-blue-800 text-center mb-6">
      {{ appStore.isTh ? header : header_en }}
    </h1>

    <div class="mb-6 max-w-3xl mx-auto">
      <label class="input input-bordered flex items-center gap-2 shadow-md w-full">
        <input
            type="text"
            class="grow"
            :placeholder="appStore.isTh ? 'ค้นหาเอกสารด้วยชื่อ...' : 'Search documents by name...'"
            v-model="searchTerm"
        />
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" class="w-4 h-4 opacity-70">
          <path fill-rule="evenodd" d="M9.965 11.023A5.996 5.996 0 0 1 5.996 12C2.686 12 0 9.314 0 5.996 0 2.686 2.686 0 5.996 0c3.308 0 5.996 2.686 5.996 5.996 0 1.544-.582 2.977-1.547 4.027l2.675 2.675c.39.39.39 1.024 0 1.414-.39.39-1.024.39-1.414 0l-2.675-2.675ZM5.996 10.5c2.47 0 4.496-2.026 4.496-4.496S8.466 1.5 5.996 1.5 1.5 3.526 1.5 6.004C1.5 8.47 3.093 10.5 5.996 10.5Z" clip-rule="evenodd" />
        </svg>
      </label>
    </div>

    <div v-if="displayedDocuments.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
      <div
          v-for="(d, i) in displayedDocuments"
          :key="d.id"
          class="card bg-base-100 shadow-xl overflow-hidden group relative"
      >
        <figure class="w-full h-48">
          <img
              :src="d.thumbnail.url"
              :alt="appStore.isTh ? d.name : d.name_en"
              class="w-full h-full object-cover"
          />
        </figure>

        <div
            class="absolute inset-0 bg-teal-700 bg-opacity-75 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300"
        >
          <div class="flex space-x-4">
            <button
                class="btn btn-circle btn-info"
                @click="openFlipBook(d)"
            >
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-6 h-6 text-white">
                <path d="M2.25 18.75a60.076 60.076 0 0 1 1.5-3.004v-7.135C3.75 6.07 4.136 5.5 4.875 5.5H8.25c.66 0 1.2.54 1.2 1.2v3.25c0 .66.54 1.2 1.2 1.2h3.25c.66 0 1.2.54 1.2 1.2v3.25c0 .66.54 1.2 1.2 1.2h3.25c.66 0 1.2.54 1.2 1.2v3.25c0 .66-.54 1.2-1.2 1.2h-3.25c-.66 0-1.2-.54-1.2-1.2v-3.25c0-.66-.54-1.2-1.2-1.2H12c-.66 0-1.2.54-1.2 1.2v3.25c0 .66-.54 1.2-1.2 1.2H4.875c-.739 0-1.125-.57-1.125-1.096v-7.135a60.076 60.076 0 0 1-1.5 3.004ZM4.875 5.5h-.125V3.75c0-.66-.54-1.2-1.2-1.2h-3.25c-.66 0-1.2.54-1.2 1.2v3.25c0 .66.54 1.2 1.2 1.2h3.25c.66 0 1.2-.54 1.2-1.2V5.5ZM12 12c0-.66.54-1.2 1.2-1.2h3.25c.66 0 1.2.54 1.2 1.2v3.25c0 .66-.54 1.2-1.2 1.2h-3.25c-.66 0-1.2-.54-1.2-1.2v-3.25Z" />
              </svg>
            </button>
            <a
                v-if="d.file && d.file.url"
                :href="d.file.url"
                target="_blank"
                class="btn btn-circle btn-info"
            >
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-6 h-6 text-white">
                <path fill-rule="evenodd" d="M11.828 2.25c-.965 0-1.75.785-1.75 1.75v14.5c0 .965.785 1.75 1.75 1.75H18.75c.965 0 1.75-.785 1.75-1.75V8.187c0-.284-.113-.559-.313-.75L15.313 3.107a1.75 1.75 0 0 0-.75-.313H11.828ZM10.5 4a.75.75 0 0 0-.75-.75H6.25A1.75 1.75 0 0 0 4.5 5.75v14.5c0 .965.785 1.75 1.75 1.75h4.25a.75.75 0 0 0 0-1.5H6.25a.25.25 0 0 1-.25-.25V5.75c0-.138.112-.25.25-.25h3.5A.75.75 0 0 0 10.5 4ZM15.75 5.5a.25.25 0 0 1 .25.25v2.25h2.25a.25.25 0 0 1 .25.25v.75H16.25a1.75 1.75 0 0 0-1.75 1.75v3.25c0 .414-.336.75-.75.75H13a.75.75 0 0 0-.75.75v.75c0 .414.336.75.75.75h1.75a.75.75 0 0 0 .75-.75v-.75a.75.75 0 0 0-.75-.75H13a.25.25 0 0 1-.25-.25V10.25c0-.138.112-.25.25-.25h2.25a.75.75 0 0 0 .75-.75V5.75Z" clip-rule="evenodd" />
              </svg>
            </a>
          </div>
        </div>

        <div class="card-body p-4">
          <h6 class="text-base font-semibold text-blue-600">
            {{ appStore.isTh ? d.name : d.name_en }}
          </h6>
        </div>
      </div>
    </div>
    <div v-else-if="searchTerm" class="text-center text-gray-500 text-lg mt-8">
      {{ appStore.isTh ? 'ไม่พบเอกสารที่ตรงกับคำค้นหา' : 'No matching documents found.' }}
    </div>
    <div v-else class="text-center text-gray-500 text-lg mt-8">
      {{ appStore.isTh ? 'กำลังโหลดเอกสาร...' : 'Loading documents...' }}
    </div>

    <div v-if="hasMoreDocuments" class="text-center mt-8">
      <button class="btn bg-[#1b3872] text-white hover:bg-[#1b3872]/90 rounded-none border-none shadow-md" @click="loadMoreDocuments">
        {{ appStore.isTh ? 'โหลดเอกสารเพิ่ม' : 'Load More' }}
      </button>
    </div>

    <div
        v-if="overlay"
        class="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50 p-4"
    >
      <div class="relative w-full h-full max-w-5xl max-h-5xl bg-base-100 rounded-box shadow-2xl">
        <button
            class="btn btn-sm btn-circle btn-error absolute top-4 right-4 z-10"
            @click="overlay = false"
        >
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5 text-white">
            <path fill-rule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25Zm-1.72 6.97a.75.75 0 1 0-1.06 1.06L10.94 12l-1.72 1.72a.75.75 0 1 0 1.06 1.06L12 13.06l1.72 1.72a.75.75 0 1 0 1.06-1.06L13.06 12l1.72-1.72a.75.75 0 1 0-1.06-1.06L12 10.94l-1.72-1.72Z" clip-rule="evenodd" />
          </svg>
        </button>

        <Flipbook ref="flipbookComponent" :pages="currentFlipbookPages" class="w-full h-full" />


        <div class="absolute bottom-4 left-1/2 -translate-x-1/2 flex space-x-2">
          <button
              class="btn btn-circle btn-sm btn-info"
              @click="flipLeft()"
          >
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5 text-white">
              <path fill-rule="evenodd" d="M7.72 12.53a.75.75 0 0 1 0-1.06l7.5-7.5a.75.75 0 1 1 1.06 1.06L9.31 12l6.97 6.97a.75.75 0 1 1-1.06 1.06l-7.5-7.5Z" clip-rule="evenodd" />
            </svg>
          </button>
          <button
              class="btn btn-circle btn-sm btn-info"
              @click="flipRight()"
          >
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-5 h-5 text-white">
              <path fill-rule="evenodd" d="M16.28 12.28a.75.75 0 0 0 0-1.06l-7.5-7.5a.75.75 0 0 0-1.06 1.06L14.69 12l-6.97 6.97a.75.75 0 1 0 1.06 1.06l7.5-7.5Z" clip-rule="evenodd" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { useInfoDisseminationStore } from '@/stores/infoDisseminationStore';
import { useAppStore } from '@/stores/app';

// Import Flipbook component
import Flipbook from 'flipbook-vue';

// Constants
const INITIAL_ITEMS = 8;
const ITEMS_PER_LOAD = 4;

const infoDisseminationStore = useInfoDisseminationStore();
const appStore = useAppStore();

const header = "เอกสารเผยแพร่";
const header_en = "HumanTech Documents";

// Reactive States
const itemsToShow = ref(INITIAL_ITEMS);
const searchTerm = ref('');

const overlay = ref(false);
const currentFlipbookPages = ref([]);
const flipbookComponent = ref(null);
const isFlipping = ref(false);

// Computed Properties
const allFilteredDocuments = computed(() => {
  let documents = infoDisseminationStore.getFilteredDocuments;

  if (searchTerm.value) {
    const lowerCaseSearchTerm = searchTerm.value.toLowerCase();
    documents = documents.filter(doc =>
        (doc.name && doc.name.toLowerCase().includes(lowerCaseSearchTerm)) ||
        (doc.name_en && doc.name_en.toLowerCase().includes(lowerCaseSearchTerm))
    );
  }
  return documents;
});

const displayedDocuments = computed(() => {
  return allFilteredDocuments.value.slice(0, itemsToShow.value);
});

const hasMoreDocuments = computed(() => {
  return itemsToShow.value < allFilteredDocuments.value.length;
});

// Watcher เพื่อรีเซ็ต itemsToShow เมื่อคำค้นหาเปลี่ยน
watch(searchTerm, () => {
  itemsToShow.value = INITIAL_ITEMS;
});

// Lifecycle Hook
onMounted(async () => {
  await infoDisseminationStore.fetchDocuments();
  // infoDisseminationStore.updatePdfDataState(); // อาจไม่จำเป็นถ้า fetchDocuments ดึงข้อมูล PDF มาพร้อมอยู่แล้ว
});

// Methods
const openFlipBook = (document) => { // เปลี่ยนจาก index เป็น document object
                                     // ตรวจสอบว่ามี images สำหรับ flipbook หรือไม่
  if (document.images && document.images.length > 0) {
    currentFlipbookPages.value = document.images.map(img => img.url); // สมมติว่า images เป็น array ของ object ที่มี url
    overlay.value = true;
  } else {
    // แจ้งเตือนผู้ใช้หากไม่มีรูปภาพสำหรับ Flipbook
    alert(appStore.isTh ? 'ไม่มีรูปภาพสำหรับ Flipbook ของเอกสารนี้' : 'No images available for Flipbook for this document.');
    console.warn('No images available for flipbook for this document:', document);
  }
};

const loadMoreDocuments = () => {
  itemsToShow.value += ITEMS_PER_LOAD;
};

const flipLeft = () => {
  // ตรวจสอบว่า flipbookComponent มีอยู่, ไม่ได้กำลังพลิกอยู่, และยังไม่ถึงหน้าแรก
  if (flipbookComponent.value && !isFlipping.value && flipbookComponent.value.currentPage > 0) {
    isFlipping.value = true;
    flipbookComponent.value.flipLeft();
    setTimeout(() => {
      isFlipping.value = false;
    }, 700); // ปรับค่านี้ให้ตรงกับระยะเวลา transition ของ Flipbook
  }
};

const flipRight = () => {
  // ตรวจสอบว่า flipbookComponent มีอยู่, ไม่ได้กำลังพลิกอยู่, และยังไม่ถึงหน้าสุดท้าย
  if (flipbookComponent.value && !isFlipping.value && flipbookComponent.value.currentPage < flipbookComponent.value.numPages) {
    isFlipping.value = true;
    flipbookComponent.value.flipRight();
    setTimeout(() => {
      isFlipping.value = false;
    }, 700); // ปรับค่านี้ให้ตรงกับระยะเวลา transition ของ Flipbook
  }
};
</script>

<style scoped>
/* สไตล์สำหรับ Flipbook และ overlay */
.flipbook {
  width: 90vw;
  height: 90vh;
  max-width: 100%;
  max-height: 100%;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
</style>