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

const route = useRoute();
const router = useRouter();
const commonSearchInput = ref(route.query.common_search_query || '');
const advancedSearchOn = ref(false);
const formData = ref({});
const metadata = ref({});
const dateRangeFrom = ref(null);
const dateRangeTo = ref(null);

// Search window types with proper mapping
const typesOfSearch = [
  { common: "Общий поиск" },
  { image: "Поиск фотодокументов" },
  { audio: "Поиск фонодокументов" },
  { video: "Поиск киновидеодокументов" }
];
const currentSearchWindow = ref("common");

// Initialize metadata structure
async function loadMetadata() {
  try {
    // Initialize common fields first
    const commonFields = {
      title: { label: "Название" },
      description: { label: "Описание" },
      date: { label: "Дата", type: "date" },
      archive_number: { label: "Архивный номер" },
      authors: { label: "Авторы" },
      personalities: { label: "Персоналии" }
    };
    metadata.value.common = formatFields(commonFields);
    console.log('Common fields initialized:', metadata.value.common);

    // Load metadata for material types
    for (const type of ['image', 'audio', 'video']) {
      const { data } = await getOptions({ url: `/api/${type}-materials/` })();
      metadata.value[type] = formatFields(data.actions.list);
      console.log(`${type} fields loaded:`, metadata.value[type]);
    }
  } catch (error) {
    console.error('Error loading metadata:', error);
  }
}

function formatFields(listData) {
  // Filter out id field and create pairs of fields
  const entries = Object.entries(listData)
    .filter(([key]) => key !== 'id')
    .map(([key, value]) => ({
      name: key,
      placeholder: value.label,
      type: value.type || 'text'
    }));

  // Create rows with two fields each
  const rows = [];
  for (let i = 0; i < entries.length; i += 2) {
    rows.push(entries.slice(i, Math.min(i + 2, entries.length)));
  }
  return rows;
}

function handleSubmit() {
  const minInputLength = 3;
  if (advancedSearchOn.value) {
    handleAdvancedSearch();
  } else if (commonSearchInput.value?.length >= minInputLength) {
    handleCommonSearch();
  }
}

function handleCommonSearch() {
  const query = {
    page: 1,
    page_size: 5,
    material_type: route.query.material_type || 'common',
    ...(commonSearchInput.value && { common_search_query: commonSearchInput.value })
  };

  // Add any filled form fields
  for (const [key, value] of Object.entries(formData.value)) {
    if (value) {
      query[`${key}__icontains`] = value;
    }
  }

  router.push({ name: "search", query });
}

function handleAdvancedSearch() {
  const query = {
    page: 1,
    page_size: 5,
    material_type: currentSearchWindow.value,
    ...(commonSearchInput.value && { common_search_query: commonSearchInput.value })
  };

  // Add form data
  for (const [key, value] of Object.entries(formData.value)) {
    if (value) {
      query[`${key}__icontains`] = value;
    }
  }

  // Add date range if present
  if (dateRangeFrom.value) {
    query.date_from = dateRangeFrom.value;
  }
  if (dateRangeTo.value) {
    query.date_to = dateRangeTo.value;
  }

  router.push({ name: "search", query });
}

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

function scrollToOneThirdHeight() {
  const height = window.innerHeight;
  window.scrollTo({
    top: height / 2,
    behavior: 'smooth'
  });
}

watch(advancedSearchOn, (newVal) => {
  if (newVal) {
    scrollToOneThirdHeight();
  }
});

// Clear form data when switching search types
watch(currentSearchWindow, () => {
  formData.value = {};
  dateRangeFrom.value = null;
  dateRangeTo.value = null;
});

onMounted(() => {
  loadMetadata();
  // Initialize form data from URL if present
  if (route.query) {
    Object.entries(route.query).forEach(([key, value]) => {
      if (key.includes('__icontains')) {
        const fieldName = key.replace('__icontains', '');
        formData.value[fieldName] = value;
      }
    });
  }
});
</script>

<template>
  <div class="home">
    <div id="datepicker-container" />
    <div class="wrapper wrapper__indent">
      <div class="search-box">
        <base-input
          @keyup.enter="handleSubmit"
          v-model="commonSearchInput"
          :value="commonSearchInput"
          style="width: 400px; padding: 24px;"
          placeholder="Я ищу"
        />
        <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
          v-model="advancedSearchOn"
          label="Расширенный поиск"
          color="primary-blue"
        />
      </div>

      <div v-if="advancedSearchOn" class="advanced-search-box">
        <v-window
          v-model="currentSearchWindow"
          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="metadata[Object.keys(item)[0]]">
                  <div
                    v-for="(row, rowIndex) in metadata[Object.keys(item)[0]]"
                    :key="rowIndex"
                    class="d-flex justify-space-between mt-5"
                  >
                    <template v-for="(field, fieldIndex) in row" :key="field.name">
                      <!-- Date inputs -->
                      <template v-if="field.type === 'date'">
                        <div class="d-flex justify-space-between 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"
                            />
                            <date-input
                              placeholder="Дата до"
                              teleport="#datepicker-container"
                              :min-date="stringToDate(dateRangeFrom)"
                              v-model="dateRangeTo"
                              style="width: 155px; margin-left: 13px"
                            />
                          </div>
                        </div>
                      </template>

                      <!-- Regular text inputs -->
                      <base-input
                        v-else
                        v-model="formData[field.name]"
                        :placeholder="field.placeholder"
                        class="base-input-size"
                        :class="{
                          'ml-10': fieldIndex === 0,
                          'mr-10': fieldIndex === row.length - 1
                        }"
                      />
                    </template>
                  </div>
                </template>
              </div>
            </v-card>
          </v-window-item>
        </v-window>
      </div>

      <router-view :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> MAKE COMMON SEASRCH FORM USE KEYS FOR FIELDS,  LIKE OTHER FORMS IN THIS COMPONENT. NOT LABEL NAMES. WRITE THE WHOLE MIDIFIED CODE