<script setup>
import { ref } from "vue";
import BaseInput from "@/components/common/BaseInput.vue";
import DateInput from "@/components/common/DateInput.vue";
import { useRoute, useRouter } from "vue-router";

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

const commonSearchInput = ref(route.query.common_search_query || "");
const advancedSearchOn = ref(route.query.is_advanced_search === "true");
const currentSearchWindow = ref(route.query.material_type || 'image');
const dateRangeFrom = ref(route.query.creation_date__gte?.split("-").reverse().join(".") || '');
const dateRangeTo = ref(route.query.creation_date__lte?.split("-").reverse().join(".") || '');
const formData = ref({
  annotation: route.query.annotation__icontains || '',
  keywords: route.query.keywords__icontains || '',
  persons: route.query.persons__icontains || '',
  creation_place: route.query.creation_place__icontains || '',
  author: route.query.author__icontains || ''
});

const typesOfSearch = [
  {image: "Поиск фотодокументов"},
  {audio: "Поиск фонодокументов"},
  {video: "Поиск киновидеодокументов"}
];


function stringToDate(dateString) {
  if (!dateString) return null;
  const [day, month, year] = dateString.split('.');
  return new Date(year, month - 1, day);
}

function formatDate(date) {
  if (!date || !(date instanceof Date)) return null;
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
}

async function handleSubmit() {
  const min_input_length = 3;

  const query = {
    page: 1,
    page_size: 5,
    material_type: currentSearchWindow.value,
  };

  if (commonSearchInput.value?.length >= min_input_length) {
    query.common_search_query = commonSearchInput.value;
  }

  if (advancedSearchOn.value) {
    query.is_advanced_search = true;

    Object.entries(formData.value).forEach(([field, value]) => {
      if (value?.length >= min_input_length) {
        query[`${field}__icontains`] = value;
      }
    });

    if (dateRangeFrom.value) {
      const fromDate = stringToDate(dateRangeFrom.value);
      if (fromDate) {
        query.creation_date__gte = formatDate(fromDate);
      }
    }

    if (dateRangeTo.value) {
      const toDate = stringToDate(dateRangeTo.value);
      if (toDate) {
        query.creation_date__lte = formatDate(toDate);
      }
    }
  }

  router.push({
   name: "search",
   query: query
 });
}
</script>

<template>
  <div class="home">
    <div class="wrapper wrapper__indent">
      <div class="search-box">
        <base-input
          :model-value="commonSearchInput"
          @update:model-value="val => commonSearchInput = val"
          @keyup.enter="handleSubmit"
          style="width: 400px; padding: 24px;"
          placeholder="Я ищу"
          :value="commonSearchInput.value"
        />
        <v-btn @click="handleSubmit" variant="outlined" class="search-button">
          <v-icon size="28" class="search-icon" color="primary">mdi-magnify</v-icon>
        </v-btn>
      </div>

      <div class="search-switch">
        <v-switch
          :model-value="advancedSearchOn"
          @update:model-value="val => advancedSearchOn = val"
          label="Расширенный поиск"
          color="primary-blue"
        />
      </div>

      <div v-if="advancedSearchOn" class="advanced-search-box">
        <v-window
          :model-value="currentSearchWindow"
          @update:model-value="val => currentSearchWindow = val"
          show-arrows
          :continuous="true"
          style="width: 1000px;"
        >
          <template v-slot:prev="{ props }">
            <button @click="props.onClick" class="arrow-button prev-arrow">
              <v-icon size="36" color="primary">mdi-chevron-left</v-icon>
            </button>
          </template>

          <template v-slot:next="{ props }">
            <button @click="props.onClick" class="arrow-button next-arrow">
              <v-icon size="36" color="primary">mdi-chevron-right</v-icon>
            </button>
          </template>

          <v-window-item
            v-for="(item, index) in typesOfSearch"
            :key="Object.keys(item)[0]"
            :value="Object.keys(item)[0]"
          >
            <v-card class="d-flex justify-center">
              <div class="search-window">
                <p class="d-block ml-10 mt-2 fs-18 fw-regular color-primary-blue">
                  {{ Object.values(item)[0] }}
                </p>
                <div class="pl-10 pr-10 pt-3">
                  <v-divider/>
                </div>

                <template v-if="currentSearchWindow === 'image'">
                  <div class="d-flex justify-space-between mt-5">
                    <base-input
                      class="base-input-size ml-10"
                      placeholder="Аннотация"
                      v-model="formData.annotation"
                      :value="route.query.annotation__icontains"
                    />
                    <base-input
                      class="base-input-size mr-10"
                      placeholder="Ключевые слова"
                      v-model="formData.keywords"
                      :value="route.query.keywords__icontains"
                    />
                  </div>

                  <div class="d-flex justify-space-between mt-5 pl-10 pr-10" style="height: 30px;">
                    <div class="d-flex justify-space-between">
                      <date-input
                        placeholder="Дата от"
                        teleport="#datepicker-container"
                        v-model="dateRangeFrom"
                        style="width: 155px; margin-right: 13px"
                        :value="route.query.creation_date__gte ? route.query.creation_date__gte.split('-').reverse().join('.') : null"
                      />
                      <date-input
                        placeholder="Дата до"
                        teleport="#datepicker-container"
                        v-model="dateRangeTo"
                        :min-date="stringToDate(dateRangeFrom)"
                        style="width: 155px; margin-left: 13px"
                        :value="route.query.creation_date__gte ? route.query.creation_date__gte.split('-').reverse().join('.') : null"
                      />
                    </div>
                    <base-input
                      class="base-input-size"
                      placeholder="Место съемки"
                      v-model="formData.creation_place"
                      :value="route.query.creation_place__icontains"
                    />
                  </div>

                  <div class="d-flex justify-space-between mt-5" style="height: 30px;">
                    <base-input
                      class="base-input-size ml-10"
                      placeholder="Персоналии"
                      v-model="formData.persons"
                      :value="route.query.persons__icontains"
                    />
                    <base-input
                      class="base-input-size mr-10"
                      placeholder="Автор съемки"
                      v-model="formData.author"
                      :value="route.query.author__icontains"
                    />
                  </div>
                </template>

                <template v-else>
                  <div class="d-flex justify-space-between mt-5">
                    <base-input class="base-input-size ml-10" placeholder="Название" />
                    <base-input class="base-input-size mr-10" placeholder="Описание" />
                  </div>

                  <div class="d-flex justify-space-between mt-5 pl-10 pr-10" style="height: 30px;">
                    <div class="d-flex justify-space-between">
                      <date-input
                        placeholder="Дата от"
                        teleport="#datepicker-container"
                        style="width: 155px; margin-right: 13px"
                      />
                      <date-input
                        placeholder="Дата до"
                        teleport="#datepicker-container"
                        style="width: 155px; margin-left: 13px"
                      />
                    </div>
                    <base-input class="base-input-size" placeholder="Архивный номер" />
                  </div>

                  <div class="d-flex justify-space-between mt-5" style="height: 30px;">
                    <base-input class="base-input-size ml-10" placeholder="Авторы" />
                    <base-input class="base-input-size mr-10" placeholder="Персоналии" />
                  </div>
                </template>
              </div>
            </v-card>
          </v-window-item>
        </v-window>
      </div>

      <router-view v-if="$route.name === 'search'" :key="route.fullPath" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.search-box {
  display: flex;
  justify-content: center;
  align-items: center;
}

.search-icon {
  height: 60px;
  width: 60px;
  border-radius: 8px;
}

.search-button {
  height: 60px;
  width: 60px;
  border: solid 1px darkgray;
  margin-left: 10px;
}

.search-switch {
  display: flex;
  justify-content: left;
  margin-left: 310px;
}

.advanced-search-box {
  display: flex;
  justify-content: center;
}

.search-window {
  width: 800px;
  height: 250px;
  padding: 15px;
}

.base-input-size {
  width: 340px!important;
  height: 20px!important;
  padding: 15px;
}

.arrow-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  opacity: 0;
  transition: opacity 0.4s ease;
  border: none;
  background: transparent;
  cursor: pointer;
}

.arrow-button.prev-arrow {
  left: 10px;
}

.arrow-button.next-arrow {
  right: 10px;
}

.advanced-search-box:hover .arrow-button {
  opacity: 1;
}

.item {
  width: 900px;
  padding: 15px;
  margin-top: 15px;
  margin-bottom: 15px;
  border: 1px solid darkgray;
  border-radius: 8px;
  display: flex;
  justify-content: left;
}

.item-label {
  display: block;
  font-size: 12px;
}
</style> почему поле common search input очищается полсе запроса?