<template>
  <VRow class="match-height">
    <VCol cols="12" md="12">
      <VCard title="Büchersuche" subtitle="Vorbeischauen – Vergleichen – Verlieben">
        <VCardTitle class="text-center text-h4 font-weight-bold">
          SKOUTZ BUCHSUCHE
        </VCardTitle>

        <!-- Fieberkurve -->
        <Fieberkurve
          ref="fieberkurveRef"
          :show-reset-button="true"
          :show-categories="true"
          @update:values="updateFieberkurveValues"
          @filter-by-row="filterByRow"
        />

        <br>


        <!-- Genres -->
        <div class="genre-section-main">
          <div
            v-for="genre in genres"
            :key="genre.value"
            class="custom-checkbox"
            :class="{ active: selectedCheckbox.includes(genre.value) }"
            @click="toggleGenre(genre.value)"
          >
            <VTooltip location="top">
              {{ genre.value }}
              <template #activator="{ props }">
                <div v-bind="props" class="icon">
                  <VIcon :icon="genre.icon.icon" />
                </div>
              </template>
            </VTooltip>
          </div>
        </div>

        <!-- Button zum Zurücksetzen der Genres -->
        <VBtn class="my-3 mx-auto d-block" color="primary" @click="clearGenres">
          Alle Genres Zurücksetzen
        </VBtn>

        <!-- Text Suchfeld -->
        <div style="padding: 0 5rem;">
          <AppTextField
            v-model="message"
            clearable
            label="Finde dein Buch!"
            placeholder="Titel / ISBN / Autor ... eingeben"
            type="text"
            class="textfield-demo-icon-slot"
          >
            <template #append>
              <VBtn :icon="$vuetify.display.smAndDown" @click="searchBooks">
                <VIcon icon="tabler-search" color="#fff" size="22" />
                <span v-if="$vuetify.display.mdAndUp" class="ms-3">Suchen</span>
              </VBtn>
            </template>
          </AppTextField>
        </div>

        <!-- Button zum Zurücksetzen der Einstellungen -->
        <VBtn
          class="my-3 mx-auto d-block"
          :color="resetFeedback ? 'success' : 'error'"
          @click="resetAllSettings"
        >
          {{ resetFeedback ? 'Zurückgesetzt!' : 'Alle Einstellungen zurücksetzen' }}
        </VBtn>

        <br />
      </VCard>
    </VCol>


    <!-- Gefundene Bücher -->
    <VCol cols="12" md="12">
      <VCard class="mb-6">
        <!-- Trefferanzahl -->
        <VCardTitle class="text-h5 px-6 pt-4 pb-2">
          {{ resultCount }} {{ resultCount === 1 ? 'Buch' : 'Bücher' }} gefunden
        </VCardTitle>
        <VDivider class="my-2" />

        <VRow>
          <VCol v-for="book in filteredBooks" :key="book.id" cols="12" sm="6" md="4">
            <VCard class="pa-2">
              <VCardText class="d-flex flex-column align-center">
                <!-- Bild -->
                <VImg
                  :src="book.image"
                  width="160"
                  height="240"
                  class="mb-3 rounded"
                  cover
                />

                <!-- Titel -->
                <div class="text-h6 font-weight-bold text-center">
                  {{ book.title }}
                </div>

                <!-- Autoren -->
                <div v-if="book.authors?.length" class="text-caption mb-2 text-center">
                  von {{ book.authors.map(a => a.name).join(', ') }}
                </div>

                <!-- Genres -->
                <div class="d-flex flex-wrap justify-center mb-2">
                  <VChip
                    v-for="genre in book.genres"
                    :key="genre"
                    color="primary"
                    size="small"
                    class="ma-1"
                  >
                    {{ genre }}
                  </VChip>
                </div>

                <!-- Beschreibung (Blurb) -->
                <div
                  class="text-truncate mb-3 text-center"
                  style="max-width: 90%; max-height: 3em; overflow: hidden;"
                >
                  {{ book.blurb }}
                </div>

                <!-- Fieberkurve -->
                <Fieberkurve
                  :is-static="true"
                  :default-values="book.fieberkurve"
                  :hide-text="true"
                />

                <!-- Aktionen -->
                <VCardActions class="justify-center mt-2">
                  <VBtn size="small" variant="outlined">
                    <VIcon icon="tabler-list-details" />
                    <span class="ms-2">Detail Seite</span>
                  </VBtn>
                  <IconBtn color="secondary" icon="tabler-share" />
                </VCardActions>
              </VCardText>
            </VCard>
          </VCol>
        </VRow>
      </VCard>
    </VCol>
  </VRow>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import Fieberkurve from "@/components/Fieberkurve.vue";
import { books } from "@/components/buecherdatenbank";
import { genres } from "@/components/genredatenbank";

const message = ref("");
const loading = ref(false);
const selectedCheckbox = ref([]);
const fieberkurveValues = ref([4, 4, 4, 4, 4]);
const fieberkurveRowFilter = ref([]);

const resultCount = computed(() => filteredBooks.value.length)

const filteredBooks = computed(() => {
  return books.filter((book) => {
    const matchesGenres =
      selectedCheckbox.value.length === 0 ||
      selectedCheckbox.value.some((genre) => book.genres.includes(genre));

    const matchesText =
      !message.value ||
      book.title.toLowerCase().includes(message.value.toLowerCase()) ||
      book.authors?.some((author) =>
        author.name.toLowerCase().includes(message.value.toLowerCase())
      ) ||
      book.isbn?.includes(message.value);

    const hasRowFilters = fieberkurveRowFilter.value.length > 0;

    const matchesFieberkurve = !hasRowFilters && fieberkurveValues.value.every((value, index) => {
      const bookValue = book.fieberkurve[index]?.value || 4;
      return value === 4 || value === bookValue;
    });

    const matchesFieberkurveRowFilters = hasRowFilters && fieberkurveRowFilter.value.every(({ rowIndex, value }) => {
      return book.fieberkurve[rowIndex]?.value === value;
    });

    return matchesGenres && matchesText && (matchesFieberkurve || matchesFieberkurveRowFilters);
  });
});

const searchBooks = () => {
  console.log("Suche gestartet mit Text:", message.value);
};

const toggleGenre = (genre) => {
  if (selectedCheckbox.value.includes(genre)) {
    selectedCheckbox.value = selectedCheckbox.value.filter((g) => g !== genre);
  } else {
    selectedCheckbox.value.push(genre);
  }
};

const clearGenres = () => {
  selectedCheckbox.value = [];
};

const fieberkurveRef = ref(null);
const resetFeedback = ref(false);

const resetAllSettings = () => {
  selectedCheckbox.value = [];
  fieberkurveRef.value?.resetSliders();
  message.value = "";
  fieberkurveRowFilter.value = [];
  resetFeedback.value = true;

  setTimeout(() => {
    resetFeedback.value = false;
  }, 1500);
};

const updateFieberkurveValues = (values) => {
  fieberkurveValues.value = values;
};

const filterByRow = (activeFilters) => {
  fieberkurveRowFilter.value = activeFilters;
  console.log("Aktive Fieberkurvenfilter:", activeFilters);
};
</script>

<style scoped lang="scss">
.genre-section-main {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  justify-content: center;
}

.genre-section-main > div {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 50px;
  height: 50px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
  cursor: pointer;
  transition: all 0.3s ease;
}

.genre-section-main > div.active {
  background-color: rgb(var(--v-theme-primary));
  color: white;
  border-color: #4e60e4;
}

.genre-section-main > div:hover {
  background-color: #e6e8f0;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.genre-section-main .icon {
  font-size: 18px;
  color: inherit;
}

.v-text-field {
  margin-bottom: 1.5rem;
}
</style>
