<template>
  <div class="preferences-view">
    <div class="preferences-container">
      <header class="preferences-header">
        <button class="back-btn" @click="$router.go(-1)">
          <i class="bi-arrow-left"></i>
        </button>
        <h1>Настройки поиска</h1>
      </header>

      <!-- Сообщение -->
      <div v-if="message" :class="['message', messageType]">
        {{ message }}
      </div>

      <div class="preferences-content">
        <!-- Предпочтения по полу -->
        <section class="preference-section">
          <h2>Пол партнера</h2>
          <div class="radio-group">
            <label class="radio-option">
              <input type="radio" v-model="preferences.gender" value="any" />
              <span class="radio-text">Любой</span>
            </label>
            <label class="radio-option">
              <input type="radio" v-model="preferences.gender" value="male" />
              <span class="radio-text">Мужской</span>
            </label>
            <label class="radio-option">
              <input type="radio" v-model="preferences.gender" value="female" />
              <span class="radio-text">Женский</span>
            </label>
            <label class="radio-option">
              <input type="radio" v-model="preferences.gender" value="other" />
              <span class="radio-text">Другой</span>
            </label>
          </div>
        </section>

        <!-- Возрастной диапазон -->
        <section class="preference-section">
          <h2>Возраст</h2>
          <div class="age-range-container">
            <div class="age-input-group">
              <label>От</label>
              <input 
                type="number" 
                v-model.number="preferences.ageRange.min" 
                min="18" 
                max="99"
                class="age-input"
              />
            </div>
            <div class="age-input-group">
              <label>До</label>
              <input 
                type="number" 
                v-model.number="preferences.ageRange.max" 
                min="18" 
                max="99"
                class="age-input"
              />
            </div>
          </div>
          <div class="age-info">
            <p v-if="currentUserAge">
              Ваш возраст: {{ currentUserAge }} лет
            </p>
          </div>
        </section>

        <!-- Предпочтения по городу -->
        <section class="preference-section">
          <h2>Местоположение</h2>
          
          <div class="toggle-option">
            <label class="toggle-label">
              <input 
                type="checkbox" 
                v-model="preferences.cityPreferences.sameCity"
                class="toggle-input"
              />
              <span class="toggle-slider"></span>
              <span class="toggle-text">
                Показывать только из моего города
                <span v-if="user?.location?.city" class="current-city">
                  ({{ user.location.city }})
                </span>
              </span>
            </label>
          </div>

          <div v-if="!preferences.cityPreferences.sameCity" class="city-preferences">
            <h3>Дополнительные города</h3>
            <div class="city-search-wrapper">
              <input
                type="text"
                v-model="citySearchQuery"
                @input="onCitySearch"
                @focus="showCityList = true"
                placeholder="Добавить город..."
                class="city-search-input"
              />
              <div v-if="showCityList && filteredCities.length > 0" class="city-dropdown">
                <div 
                  v-for="city in filteredCities"
                  :key="city"
                  @click="addAllowedCity(city)"
                  class="city-option"
                >
                  {{ city }}
                </div>
              </div>
            </div>
            
            <div v-if="preferences.cityPreferences.allowedCities.length > 0" class="allowed-cities">
              <div 
                v-for="(city, index) in preferences.cityPreferences.allowedCities"
                :key="index"
                class="city-tag"
              >
                <span>{{ city }}</span>
                <button @click="removeAllowedCity(index)" class="remove-city-btn">
                  <i class="bi-x"></i>
                </button>
              </div>
            </div>
          </div>
        </section>

        <!-- Кнопка сохранения -->
        <div class="save-section">
          <button 
            @click="savePreferences" 
            :disabled="loading"
            class="save-btn"
          >
            <span v-if="loading">Сохранение...</span>
            <span v-else>Сохранить настройки</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useAuth } from '@/auth'
import api from '@/services/api'
import citiesData from '@/assets/russian-cities.json'

export default {
  name: 'PreferencesView',
  setup() {
    const { user } = useAuth()
    const loading = ref(false)
    const message = ref('')
    const messageType = ref('') // 'success' или 'error'
    
    // Данные предпочтений
    const preferences = ref({
      gender: 'any',
      ageRange: {
        min: 20,
        max: 35
      },
      cityPreferences: {
        sameCity: true,
        allowedCities: []
      }
    })

    // Поля для поиска городов
    const citySearchQuery = ref('')
    const showCityList = ref(false)
    const filteredCities = ref([])

    // Вычисляемые свойства
    const currentUserAge = computed(() => {
      if (!user.value?.dateOfBirth) return null
      const birthDate = new Date(user.value.dateOfBirth)
      const today = new Date()
      let age = today.getFullYear() - birthDate.getFullYear()
      const m = today.getMonth() - birthDate.getMonth()
      if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--
      }
      return age
    })

    // Установка дефолтного возрастного диапазона на основе возраста пользователя
    const setDefaultAgeRange = () => {
      if (currentUserAge.value) {
        preferences.value.ageRange.min = Math.max(18, currentUserAge.value - 2)
        preferences.value.ageRange.max = Math.min(99, currentUserAge.value + 2)
      }
    }

    // Загрузка предпочтений пользователя
    const loadUserPreferences = async () => {
      if (!user.value) return
      
      loading.value = true
      try {
        // Берем данные из store, если они есть
        if (user.value.preferences) {
          preferences.value = {
            gender: user.value.preferences.gender || 'any',
            ageRange: {
              min: user.value.preferences.ageRange?.min || (currentUserAge.value ? currentUserAge.value - 2 : 20),
              max: user.value.preferences.ageRange?.max || (currentUserAge.value ? currentUserAge.value + 2 : 35)
            },
            cityPreferences: {
              sameCity: user.value.preferences.cityPreferences?.sameCity ?? true,
              allowedCities: user.value.preferences.cityPreferences?.allowedCities || []
            }
          }
        } else {
          setDefaultAgeRange()
        }
      } catch (error) {
        console.error('Ошибка при загрузке предпочтений:', error)
        showMessage('Ошибка при загрузке предпочтений', 'error')
      } finally {
        loading.value = false
      }
    }

    // Поиск городов
    const onCitySearch = (event) => {
      const query = event.target.value.toLowerCase().trim()
      citySearchQuery.value = event.target.value
      
      if (query.length > 0) {
        filteredCities.value = citiesData
          .filter(city => city.name && city.name.trim()) // Фильтруем только записи с названием
          .map(city => city.name)
          .filter(city => city.toLowerCase().includes(query))
          .slice(0, 10)
        showCityList.value = filteredCities.value.length > 0
      } else {
        filteredCities.value = []
        showCityList.value = false
      }
    }

    // Добавление города в разрешенные
    const addAllowedCity = (city) => {
      if (!preferences.value.cityPreferences.allowedCities.includes(city)) {
        preferences.value.cityPreferences.allowedCities.push(city)
      }
      citySearchQuery.value = ''
      showCityList.value = false
    }

    // Удаление города из разрешенных
    const removeAllowedCity = (index) => {
      preferences.value.cityPreferences.allowedCities.splice(index, 1)
    }

    // Сохранение предпочтений
    const savePreferences = async () => {
      loading.value = true
      try {
        const response = await api.updateUserProfile({
          preferences: preferences.value
        })
        
        // Обновляем данные пользователя в локальном состоянии
        if (response.data && user.value) {
          user.value = { ...user.value, ...response.data }
        }
        
        showMessage('Предпочтения успешно сохранены!', 'success')
      } catch (error) {
        console.error('Ошибка при сохранении предпочтений:', error)
        showMessage('Ошибка при сохранении предпочтений', 'error')
      } finally {
        loading.value = false
      }
    }

    // Показ сообщения
    const showMessage = (text, type) => {
      message.value = text
      messageType.value = type
      setTimeout(() => {
        message.value = ''
        messageType.value = ''
      }, 3000)
    }

    // Закрытие выпадающего списка при клике вне его
    const handleClickOutside = (event) => {
      if (!event.target.closest('.city-search-wrapper')) {
        showCityList.value = false
      }
    }

    onMounted(() => {
      loadUserPreferences()
      document.addEventListener('click', handleClickOutside)
    })

    return {
      loading,
      message,
      messageType,
      preferences,
      citySearchQuery,
      showCityList,
      filteredCities,
      user,
      currentUserAge,
      onCitySearch,
      addAllowedCity,
      removeAllowedCity,
      savePreferences,
      setDefaultAgeRange
    }
  }
}
</script>

<style scoped>
.preferences-view {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0;
}

.preferences-container {
  max-width: 600px;
  margin: 0 auto;
  background: white;
  min-height: 100vh;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

.preferences-header {
  display: flex;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #e2e8f0;
  background: white;
  position: sticky;
  top: 0;
  z-index: 10;
}

.back-btn {
  background: none;
  border: none;
  font-size: 1.2rem;
  color: #667eea;
  cursor: pointer;
  padding: 0.5rem;
  margin-right: 1rem;
  border-radius: 50%;
  transition: background-color 0.2s;
}

.back-btn:hover {
  background-color: #f1f5f9;
}

.preferences-header h1 {
  margin: 0;
  font-size: 1.5rem;
  color: #1e293b;
  font-weight: 600;
}

.message {
  margin: 1rem;
  padding: 0.75rem;
  border-radius: 8px;
  text-align: center;
  font-weight: 500;
}

.message.success {
  background-color: #dcfce7;
  color: #166534;
  border: 1px solid #bbf7d0;
}

.message.error {
  background-color: #fef2f2;
  color: #dc2626;
  border: 1px solid #fecaca;
}

.preferences-content {
  padding: 1rem;
}

.preference-section {
  margin-bottom: 2rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid #e2e8f0;
}

.preference-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.preference-section h2 {
  margin: 0 0 1rem 0;
  font-size: 1.2rem;
  color: #1e293b;
  font-weight: 600;
}

.preference-section h3 {
  margin: 1rem 0 0.5rem 0;
  font-size: 1rem;
  color: #475569;
  font-weight: 500;
}

.radio-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.radio-option {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 8px;
  transition: background-color 0.2s;
}

.radio-option:hover {
  background-color: #f8fafc;
}

.radio-option input[type="radio"] {
  margin-right: 0.75rem;
  accent-color: #667eea;
}

.radio-text {
  font-size: 1rem;
  color: #374151;
}

.age-range-container {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
}

.age-input-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.age-input-group label {
  font-size: 0.875rem;
  color: #6b7280;
  font-weight: 500;
}

.age-input {
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.2s;
}

.age-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.age-info {
  background-color: #f8fafc;
  padding: 1rem;
  border-radius: 8px;
  text-align: center;
}

.age-info p {
  margin: 0 0 0.5rem 0;
  color: #6b7280;
  font-size: 0.875rem;
}

.default-range-btn {
  background: #667eea;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: background-color 0.2s;
}

.default-range-btn:hover {
  background: #5a67d8;
}

.toggle-option {
  margin-bottom: 1rem;
}

.toggle-label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.toggle-input {
  display: none;
}

.toggle-slider {
  width: 50px;
  height: 26px;
  background-color: #cbd5e0;
  border-radius: 13px;
  position: relative;
  margin-right: 0.75rem;
  transition: background-color 0.2s;
}

.toggle-slider::before {
  content: '';
  position: absolute;
  width: 22px;
  height: 22px;
  background-color: white;
  border-radius: 50%;
  top: 2px;
  left: 2px;
  transition: transform 0.2s;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toggle-input:checked + .toggle-slider {
  background-color: #667eea;
}

.toggle-input:checked + .toggle-slider::before {
  transform: translateX(24px);
}

.toggle-text {
  font-size: 1rem;
  color: #374151;
}

.current-city {
  color: #6b7280;
  font-size: 0.875rem;
}

.city-preferences {
  margin-top: 1rem;
}

.city-search-wrapper {
  position: relative;
  margin-bottom: 1rem;
}

.city-search-input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.2s;
}

.city-search-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.city-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  max-height: 200px;
  overflow-y: auto;
  z-index: 20;
}

.city-option {
  padding: 0.75rem;
  cursor: pointer;
  transition: background-color 0.2s;
  border-bottom: 1px solid #f1f5f9;
}

.city-option:hover {
  background-color: #f8fafc;
}

.city-option:last-child {
  border-bottom: none;
}

.allowed-cities {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.city-tag {
  display: flex;
  align-items: center;
  background-color: #667eea;
  color: white;
  padding: 0.5rem 0.75rem;
  border-radius: 20px;
  font-size: 0.875rem;
}

.remove-city-btn {
  background: none;
  border: none;
  color: white;
  margin-left: 0.5rem;
  cursor: pointer;
  font-size: 1rem;
  padding: 0;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.remove-city-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.save-section {
  margin-top: 2rem;
  padding-top: 1.5rem;
  border-top: 1px solid #e2e8f0;
}

.save-btn {
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 1rem;
  border-radius: 12px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.save-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.save-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

@media (max-width: 768px) {
  .preferences-container {
    box-shadow: none;
  }
  
  .age-range-container {
    flex-direction: column;
  }
  
  .radio-group {
    gap: 0.25rem;
  }
}
</style>