<template>
  <div class="search-form">
    <div v-html="$t('search_title')"></div>
    
    <form @submit.prevent="handleSearch">
      <div class="form-row">
        <label>{{ $t('search_username_includes') }}</label>
        <input v-model="searchData.nameIncludes" type="text" />
      </div>
      
      <div class="form-row form-row-age">
        <div class="age-input-group">
          <label>{{ $t('search_from_age') }}</label>
          <input v-model.number="searchData.minAge" type="number" min="18" max="120" />
        </div>
        <div class="age-input-group">
          <label>{{ $t('search_to_age') }}</label>
          <input v-model.number="searchData.maxAge" type="number" min="18" max="120" />
        </div>
      </div>
      
      <div class="form-row">
        <label>{{ $t('search_country') }}</label>
        <select v-model="selectedCountries" multiple>
          <option v-for="(code, name) in countries" :key="code" :value="name">
            {{ name }}
          </option>
        </select>
      </div>
      
      <div class="form-row">
        <label>{{ $t('search_genders') }}</label>
        <Multiselect
          v-model="searchData.genders"
          :options="translatedGenderOptions"
          mode="multiple"
          :close-on-select="false"
          :searchable="true"
          :placeholder="$t('search_all')"
          track-by="value"
          label="label"
          value-prop="value"
          :hide-selected="false"
          :can-deselect="true"
          :create-option="false"
        />
      </div>
      
      <div class="form-row">
        <button type="submit">{{ $t('search_button') }}</button>
      </div>
    </form>
    
    <div v-if="chatStore.searchResults.length > 0" class="search-results">
      <div
        v-for="user in chatStore.searchResults"
        :key="user.sessionId"
        class="search-result-item"
        @click="selectUser(user.userName)"
      >
        <img
          v-if="user.isoCountryCode"
          :src="`/static/flags/${user.isoCountryCode}.png`"
          :alt="user.country"
          style="width: 16px; height: 12px; margin-right: 5px;"
        />
        {{ user.userName }} ({{ user.age }}, {{ user.gender }}, {{ user.country }})
      </div>
    </div>
    
    <div v-else-if="hasSearched && chatStore.searchResults.length === 0" class="search-results">
      <p>{{ $t('search_no_results') }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useChatStore } from '../stores/chat';
import { useI18n } from 'vue-i18n';
import countryTranslations from '../i18n/countries.json';
import Multiselect from '@vueform/multiselect';
import '@vueform/multiselect/themes/default.css';

const { locale, t } = useI18n();
const chatStore = useChatStore();
const countriesRaw = ref({});

// Geschlechter-Optionen für Multiselect
const genderOptions = [
  { value: 'F', label: 'gender_female' },
  { value: 'M', label: 'gender_male' },
  { value: 'P', label: 'gender_pair' },
  { value: 'TF', label: 'gender_trans_mf' },
  { value: 'TM', label: 'gender_trans_fm' }
];

// Übersetzte Geschlechter-Optionen
const translatedGenderOptions = computed(() => {
  return genderOptions.map(option => ({
    value: option.value,
    label: t(option.label)
  }));
});

// Übersetzte Länderliste (sortiert)
const countries = computed(() => {
  const translated = {};
  const translations = countryTranslations[locale.value] || countryTranslations['en'] || {};
  
  for (const [englishName, code] of Object.entries(countriesRaw.value)) {
    // Verwende Übersetzung falls vorhanden, sonst englischen Namen
    translated[translations[englishName] || englishName] = code;
  }
  
  // Sortiere alphabetisch nach übersetztem Namen
  const sorted = {};
  Object.keys(translated).sort((a, b) => a.localeCompare(b, locale.value)).forEach(key => {
    sorted[key] = translated[key];
  });
  
  return sorted;
});

// Verwende searchData direkt aus dem Store, damit die Daten beim View-Wechsel erhalten bleiben
const searchData = chatStore.searchData;

const selectedCountries = computed({
  get: () => chatStore.searchData.selectedCountries || [],
  set: (value) => {
    chatStore.searchData.selectedCountries = value;
  }
});

// Prüfe, ob eine Suche durchgeführt wurde (wenn searchResults leer ist, aber searchData ausgefüllt ist)
const hasSearched = computed(() => {
  const data = chatStore.searchData;
  return data.nameIncludes || data.minAge || data.maxAge || 
         (data.selectedCountries && data.selectedCountries.length > 0) || 
         (data.genders && data.genders.length > 0);
});

onMounted(async () => {
  try {
    const response = await axios.get('/api/countries');
    countriesRaw.value = response.data;
  } catch (error) {
    console.error('Fehler beim Laden der Länderliste:', error);
  }
});

function handleSearch() {
  if (chatStore.searchData.minAge && chatStore.searchData.maxAge && chatStore.searchData.minAge > chatStore.searchData.maxAge) {
    alert(chatStore.$i18n?.t('search_min_age_error') || 'Das Mindestalter muss mindestens so groß sein wie das Höchstalter.');
    return;
  }
  
  // Konvertiere übersetzte Ländernamen zurück zu englischen Namen
  const translations = countryTranslations[locale.value] || countryTranslations['en'] || {};
  const englishCountryNames = (chatStore.searchData.selectedCountries || []).map(translatedName => {
    // Suche den englischen Namen
    for (const [englishName, translated] of Object.entries(translations)) {
      if (translated === translatedName) {
        return englishName;
      }
    }
    return translatedName; // Fallback: verwende den Namen wie er ist
  });
  
  // Konvertiere Multiselect-Werte zu Array von Strings (falls Objekte)
  const genderValues = Array.isArray(chatStore.searchData.genders) 
    ? chatStore.searchData.genders.map(g => typeof g === 'object' ? g.value : g)
    : [];
  
  const searchPayload = {
    nameIncludes: chatStore.searchData.nameIncludes || null,
    minAge: chatStore.searchData.minAge || null,
    maxAge: chatStore.searchData.maxAge || null,
    countries: englishCountryNames.length > 0 ? englishCountryNames : null,
    genders: genderValues.length > 0 ? genderValues : null
  };
  
  // Speichere auch die englischen Länder-Namen im Store für spätere Aktualisierungen
  chatStore.searchData.selectedCountriesEnglish = englishCountryNames.length > 0 ? englishCountryNames : [];
  
  chatStore.userSearch(searchPayload);
}

function selectUser(userName) {
  chatStore.requestConversation(userName);
}
</script>

<style scoped>
.form-row-age {
  display: flex;
  gap: 1em;
  align-items: center;
}

.age-input-group {
  display: flex;
  flex-direction: row;
  align-items: center;
  flex: 1;
  gap: 0.5em;
}

.age-input-group label {
  margin-bottom: 0;
  white-space: nowrap;
}

/* Multiselect Styling */
:deep(.multiselect-wrapper) {
  flex: 1;
}

:deep(.multiselect) {
  min-height: auto;
}

:deep(.multiselect-input-wrapper) {
  display: flex !important;
  flex-wrap: wrap !important;
  align-items: center;
  gap: 0.25em;
  padding: 0.25em;
  min-height: 2em;
  position: relative;
}

:deep(.multiselect-input-wrapper > *) {
  flex-shrink: 0;
}

:deep(.multiselect-tags) {
  min-height: 2em;
  display: flex !important;
  flex-wrap: wrap !important;
  gap: 0.25em;
  padding: 0;
  margin: 0;
  flex: 1;
  width: 100%;
}

:deep(.multiselect.is-open .multiselect-tags) {
  display: flex !important;
}

:deep(.multiselect:not(.is-open) .multiselect-tags) {
  display: flex !important;
}

:deep(.multiselect-tag) {
  background: #429043;
  color: white;
  padding: 0.25em 0.5em;
  margin: 0;
  border-radius: 3px;
  display: inline-flex !important;
  align-items: center;
  gap: 0.25em;
  font-size: 0.9em;
  visibility: visible !important;
  opacity: 1 !important;
}

:deep(.multiselect-tag i) {
  color: white;
  opacity: 0.8;
  cursor: pointer;
  margin-left: 0.25em;
}

:deep(.multiselect-tag i:hover) {
  opacity: 1;
}

:deep(.multiselect-placeholder) {
  color: #999;
}

:deep(.multiselect-single-label) {
  display: none !important;
}

:deep(.multiselect-multiple-label) {
  display: none !important;
}

:deep(.multiselect-tags-text) {
  display: none !important;
}

:deep(.multiselect-search) {
  display: block !important;
  flex: 0 0 auto;
  min-width: 20px;
  max-width: 50px;
  opacity: 0.3;
  pointer-events: none;
}

:deep(.multiselect-tags-search) {
  display: flex !important;
  flex-wrap: wrap !important;
  gap: 0.25em;
  padding: 0;
  margin: 0;
  flex: 1;
}

:deep(.multiselect-tags-search .multiselect-tag) {
  background: #429043;
  color: white;
  padding: 0.25em 0.5em;
  margin: 0;
  border-radius: 3px;
  display: inline-flex !important;
  align-items: center;
  gap: 0.25em;
  font-size: 0.9em;
  visibility: visible !important;
  opacity: 1 !important;
}

:deep(.multiselect-input) {
  flex: 0 0 auto;
  min-width: 50px;
}

:deep(.multiselect.is-active) {
  border-color: #429043;
}

:deep(.multiselect.is-active .multiselect-tags) {
  display: flex !important;
}

:deep(.multiselect:not(.is-active) .multiselect-tags) {
  display: flex !important;
}

:deep(.multiselect-single) {
  display: none !important;
}

:deep(.multiselect-multiple) {
  display: block !important;
}
</style>

glich werde