<template>
  <div class="search-form">
    <div class="panel-header" 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>
        <Multiselect
          v-model="selectedCountries"
          :options="countryOptions"
          mode="tags"
          :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">
        <label>{{ $t('search_genders') }}</label>
        <Multiselect
          v-model="searchData.genders"
          :options="translatedGenderOptions"
          mode="tags"
          :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"
          class="search-flag"
        />
        <span class="search-result-main">
          <strong>{{ user.userName }}</strong>
          <span>{{ user.country }}</span>
        </span>
        <span class="search-result-meta">{{ user.age }} · {{ user.gender }}</span>
      </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(() => {
  const ownGender = chatStore.gender;
  const preferredOrder = ownGender === 'M'
    ? ['F', 'M', 'P', 'TF', 'TM']
    : ownGender === 'F'
      ? ['M', 'F', 'P', 'TF', 'TM']
      : genderOptions.map(option => option.value);

  const orderIndex = new Map(preferredOrder.map((value, index) => [value, index]));
  const sortedOptions = [...genderOptions].sort((a, b) => {
    return (orderIndex.get(a.value) ?? 999) - (orderIndex.get(b.value) ?? 999);
  });

  return sortedOptions.map(option => ({
    value: option.value,
    label: t(option.label)
  }));
});

// Übersetzte Länderliste mit stabilem Wert (englischer Ländername)
const countries = computed(() => {
  const translations = countryTranslations[locale.value] || countryTranslations.en || {};
  const list = Object.entries(countriesRaw.value).map(([englishName, isoCode]) => ({
    label: translations[englishName] || englishName,
    value: englishName,
    isoCode
  }));

  list.sort((a, b) => a.label.localeCompare(b.label, locale.value));
  return list;
});

const countryOptions = computed(() => {
  const options = [...countries.value];
  const ownCountry = chatStore.country;
  if (!ownCountry) return options;

  // Priorisiere das eigene Land anhand des stabilen Werts (englischer Ländername).
  // Fallback: vergleiche zusätzlich das übersetzte Label, falls der Wert bereits lokalisiert gespeichert wurde.
  const translations = countryTranslations[locale.value] || countryTranslations['en'] || {};
  const ownCountryTranslated = translations[ownCountry] || ownCountry;
  const ownCountryIndex = options.findIndex(option => (
    option.value === ownCountry || option.label === ownCountry || option.label === ownCountryTranslated
  ));
  if (ownCountryIndex <= 0) return options;

  const [ownCountryOption] = options.splice(ownCountryIndex, 1);
  options.unshift(ownCountryOption);
  return options;
});

// 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?.length
    ? chatStore.searchData.selectedCountries
    : (chatStore.searchData.selectedCountriesEnglish || []),
  set: (value) => {
    chatStore.searchData.selectedCountries = value;
    chatStore.searchData.selectedCountriesEnglish = 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;
  }
  
  const englishCountryNames = chatStore.searchData.selectedCountries || [];
  
  // 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
  };
  
  chatStore.searchData.selectedCountriesEnglish = englishCountryNames.length > 0 ? englishCountryNames : [];
  
  chatStore.userSearch(searchPayload);
}

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

<style scoped>
.panel-header {
  margin-bottom: 16px;
}

.search-result-item {
  display: grid;
  grid-template-columns: 28px minmax(0, 1fr) auto;
  gap: 8px;
  align-items: center;
  border-radius: 10px;
}

.search-flag {
  width: 28px;
  height: 20px;
  border-radius: 5px;
  border: 1px solid #d7dfd9;
}

.search-result-main {
  min-width: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  overflow: hidden;
}

.search-result-main strong {
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #18201b;
}

.search-result-main span {
  color: #637067;
  white-space: nowrap;
}

.search-result-meta {
  font-size: 12px;
  font-weight: 600;
  color: #536159;
  white-space: nowrap;
}

.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: 38px;
  border: 0;
  border-radius: var(--radius-sm);
  background: var(--color-surface);
  box-shadow: inset 0 0 0 1px var(--color-border);
}

:deep(.multiselect-wrapper),
:deep(.multiselect-tags-search-wrapper),
:deep(.multiselect-tags-search-copy) {
  border: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

:deep(.multiselect-input-wrapper) {
  padding: 4px 6px;
  min-height: 36px;
}

:deep(.multiselect-tags) {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 4px;
  min-height: 24px;
  padding: 0;
  margin: 0;
}

:deep(.multiselect-tag) {
  background: #3d8654;
  color: white;
  padding: 3px 8px;
  margin: 0;
  border-radius: 999px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  line-height: 1.2;
}

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

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

:deep(.multiselect-placeholder) {
  color: #8a948e;
  font-size: 13px;
}

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

:deep(.multiselect-search) {
  min-width: 80px;
  font-size: 13px;
  color: #18201b;
  border: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

:deep(.multiselect-input) {
  min-height: 22px;
  border: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

:deep(.multiselect-tags-search) {
  border: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

:deep(.multiselect.is-active) {
  box-shadow:
    inset 0 0 0 1px #3d8654,
    0 0 0 3px rgba(61, 134, 84, 0.12);
}
</style>
