<template>
  <div class="page events-page">
    <div class="page-header">
      <button class="btn btn-back" @click="$router.go(-1)">← Назад</button>
      <h1>📅 События</h1>
    </div>

    <div class="events-controls">
      <div class="tabs">
        <button 
          class="tab-button" 
          :class="{ active: activeTab === 'upcoming' }"
          @click="activeTab = 'upcoming'"
        >
          🔮 Предстоящие
        </button>
        <button 
          class="tab-button" 
          :class="{ active: activeTab === 'my' }"
          @click="activeTab = 'my'"
        >
          🎫 Мои регистрации
        </button>
        <button 
          class="tab-button" 
          :class="{ active: activeTab === 'past' }"
          @click="activeTab = 'past'"
        >
          📚 Прошедшие
        </button>
      </div>

      <div class="filters">
        <select v-model="typeFilter" @change="applyFilters">
          <option value="">Все типы</option>
          <option value="race">Забеги</option>
          <option value="training">Тренировки</option>
          <option value="social">Встречи</option>
          <option value="workshop">Семинары</option>
        </select>
      </div>
    </div>

    <div v-if="loading" class="loading">Загрузка событий...</div>

    <div v-else class="events-content">
      <!-- Предстоящие события -->
      <div v-if="activeTab === 'upcoming'" class="events-section">
        <h2>🔮 Предстоящие события</h2>
        <div v-if="!filteredUpcomingEvents || filteredUpcomingEvents.length === 0" class="empty-state">
          <p>Нет предстоящих событий</p>
          <button class="btn btn-primary" @click="refreshEvents">
            🔄 Обновить
          </button>
        </div>
        <div v-else class="events-grid">
          <EventCard 
            v-for="event in filteredUpcomingEvents" 
            :key="event.id"
            :event="event"
            :user-registrations="userRegistrations"
            @register="handleRegister"
            @view-details="viewEventDetails"
          />
        </div>
      </div>

      <!-- Мои регистрации -->
      <div v-if="activeTab === 'my'" class="events-section">
        <h2>🎫 Мои регистрации</h2>
        <div v-if="(!registeredEvents || registeredEvents.length === 0) && (!pendingRegistrations || pendingRegistrations.length === 0)" class="empty-state">
          <p>У вас нет зарегистрированных событий</p>
          <button class="btn btn-primary" @click="activeTab = 'upcoming'">
            📅 Посмотреть события
          </button>
        </div>
        
        <div v-if="pendingRegistrations && pendingRegistrations.length > 0" class="registrations-section">
          <h3>⏳ Ожидают подтверждения</h3>
          <div class="registrations-list">
            <RegistrationCard 
              v-for="registration in pendingRegistrations"
              :key="registration.id"
              :registration="registration"
              @cancel="handleCancelRegistration"
            />
          </div>
        </div>

        <div v-if="registeredEvents && registeredEvents.length > 0" class="registrations-section">
          <h3>✅ Подтвержденные участия</h3>
          <div class="events-grid">
            <EventCard 
              v-for="event in registeredEvents" 
              :key="event.id"
              :event="event"
              :user-registrations="userRegistrations"
              :show-actions="true"
              @cancel="handleCancelRegistration"
              @view-details="viewEventDetails"
            />
          </div>
        </div>
      </div>

      <!-- Прошедшие события -->
      <div v-if="activeTab === 'past'" class="events-section">
        <h2>📚 Прошедшие события</h2>
        <div v-if="!pastEvents || pastEvents.length === 0" class="empty-state">
          <p>Нет прошедших событий</p>
        </div>
        <div v-else class="events-grid">
          <EventCard 
            v-for="event in pastEvents" 
            :key="event.id"
            :event="event"
            :user-registrations="userRegistrations"
            :show-actions="false"
            @view-details="viewEventDetails"
          />
        </div>
      </div>
    </div>

    <div v-if="error" class="error-message">
      {{ error }}
      <button class="btn-retry" @click="loadEventsData">Попробовать снова</button>
    </div>

    <!-- Модальное окно регистрации -->
    <div v-if="showRegistrationModal" class="modal-overlay" @click="closeRegistrationModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>🎫 Регистрация на событие</h3>
          <button class="btn-close" @click="closeRegistrationModal">×</button>
        </div>
        
        <div v-if="selectedEvent" class="event-preview">
          <h4>{{ selectedEvent.title }}</h4>
          <div class="event-details">
            <div class="detail">
              <span class="icon">📅</span>
              <span>{{ formatDate(selectedEvent.date) }}</span>
            </div>
            <div class="detail">
              <span class="icon">📍</span>
              <span>{{ selectedEvent.location }}</span>
            </div>
            <div v-if="selectedEvent.distance" class="detail">
              <span class="icon">🏃</span>
              <span>{{ selectedEvent.distance }}</span>
            </div>
          </div>
          
          <!-- Проверка доступности -->
          <div v-if="availabilityCheck" class="availability-info">
            <div v-if="availabilityCheck.available" class="available">
              ✅ Есть свободные места 
              <span v-if="availabilityCheck.remaining_spots > 0">
                (осталось: {{ availabilityCheck.remaining_spots }})
              </span>
            </div>
            <div v-else class="not-available">
              ❌ Регистрация закрыта или нет свободных мест
            </div>
          </div>
        </div>
        
        <form @submit.prevent="confirmRegistration">
          <div class="form-group">
            <label>Дополнительные заметки (необязательно)</label>
            <textarea 
              v-model="registrationNotes" 
              placeholder="Например: Участвую в дистанции 10км, особые пожелания, диетические ограничения..."
              rows="4"
              maxlength="500"
            ></textarea>
            <div class="char-count">{{ registrationNotes.length }}/500</div>
          </div>
          
          <div class="form-info">
            <p>📝 После регистрации вы получите подтверждение на email и сможете отслеживать статус в разделе "Мои регистрации".</p>
          </div>
          
          <div class="modal-actions">
            <button 
              type="submit" 
              class="btn btn-primary" 
              :disabled="registering || !availabilityCheck?.available"
            >
              {{ registering ? '⏳ Регистрируем...' : '✅ Зарегистрироваться' }}
            </button>
            <button 
              type="button" 
              class="btn btn-outline" 
              @click="closeRegistrationModal"
              :disabled="registering"
            >
              Отмена
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Уведомление об успехе -->
    <div v-if="showSuccessNotification" class="notification success">
      <div class="notification-content">
        <span>✅ Вы успешно зарегистрировались на событие!</span>
        <button class="btn-close" @click="showSuccessNotification = false">×</button>
      </div>
    </div>
  </div>
</template>

<script>
import { useEventsStore } from '../stores/event'
import { ref, onMounted, computed, watch } from 'vue'

// Импортируем компоненты как default
import EventCard from '../components/EventCard.vue'
import RegistrationCard from '../components/RegistrationCard.vue'

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: 'Events',
  components: {
    EventCard,
    RegistrationCard
  },
  setup() {
    const eventsStore = useEventsStore()
    
    // Состояние
    const activeTab = ref('upcoming')
    const typeFilter = ref('')
    const showRegistrationModal = ref(false)
    const selectedEvent = ref(null)
    const registrationNotes = ref('')
    const registering = ref(false)
    const availabilityCheck = ref(null)
    const showSuccessNotification = ref(false)
    
    // Computed - добавляем безопасные проверки
    const filteredUpcomingEvents = computed(() => {
      let events = eventsStore.upcomingEvents || []
      if (typeFilter.value && events) {
        events = events.filter(event => event && event.type === typeFilter.value)
      }
      return events || []
    })
    
    // Watch для проверки доступности при выборе события
    watch(selectedEvent, async (newEvent) => {
      if (newEvent) {
        const result = await eventsStore.checkEventAvailability(newEvent.id)
        if (result.success) {
          availabilityCheck.value = result.data
        }
      } else {
        availabilityCheck.value = null
      }
    })
    
    // Методы
    const loadEventsData = async () => {
      try {
        await Promise.all([
          eventsStore.fetchEvents(),
          eventsStore.fetchUserRegistrations()
        ])
      } catch (error) {
        console.error('Error loading events data:', error)
      }
    }
    
    const refreshEvents = async () => {
      await loadEventsData()
    }
    
    const applyFilters = () => {
      // Фильтры применяются в computed свойствах
    }
    
    const handleRegister = async (event) => {
      if (!event) return
      
      selectedEvent.value = event
      registrationNotes.value = ''
      showRegistrationModal.value = true
      
      // Проверяем доступность
      try {
        const result = await eventsStore.checkEventAvailability(event.id)
        if (result.success) {
          availabilityCheck.value = result.data
        }
      } catch (error) {
        console.error('Error checking availability:', error)
      }
    }
    
    const confirmRegistration = async () => {
      if (!selectedEvent.value || !availabilityCheck.value?.available) return
      
      registering.value = true
      try {
        const result = await eventsStore.registerForEvent(
          selectedEvent.value.id, 
          registrationNotes.value
        )
        
        if (result.success) {
          closeRegistrationModal()
          showSuccessNotification.value = true
          // Автоматически скрываем уведомление через 5 секунд
          setTimeout(() => {
            showSuccessNotification.value = false
          }, 5000)
          
          // Переключаемся на вкладку "Мои регистрации"
          activeTab.value = 'my'
        } else {
          alert('Ошибка при регистрации: ' + result.error)
        }
      } catch (error) {
        console.error('Registration error:', error)
        alert('Ошибка при регистрации: ' + error.message)
      } finally {
        registering.value = false
      }
    }
    
    const handleCancelRegistration = async (registrationId) => {
      if (confirm('Вы уверены, что хотите отменить регистрацию?')) {
        try {
          const result = await eventsStore.cancelRegistration(registrationId)
          if (result.success) {
            // Показываем уведомление об отмене
            alert('Регистрация успешно отменена')
          } else {
            alert('Ошибка при отмене регистрации: ' + result.error)
          }
        } catch (error) {
          console.error('Cancel registration error:', error)
          alert('Ошибка при отмене регистрации: ' + error.message)
        }
      }
    }
    
    const viewEventDetails = (eventId) => {
      // Переход на страницу деталей события
      // Можно реализовать позже отдельную страницу
      const event = eventsStore.events.find(e => e && e.id === parseInt(eventId))
      if (event) {
        alert(`Детали события: ${event.title}\n\n${event.description}`)
      }
    }
    
    const closeRegistrationModal = () => {
      if (!registering.value) {
        showRegistrationModal.value = false
        selectedEvent.value = null
        registrationNotes.value = ''
        availabilityCheck.value = null
      }
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return ''
      try {
        return new Date(dateString).toLocaleDateString('ru-RU', {
          day: 'numeric',
          month: 'long',
          year: 'numeric',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch (error) {
        console.error('Date formatting error:', error)
        return dateString
      }
    }
    
    onMounted(() => {
      loadEventsData()
    })
    
    return {
      loading: computed(() => eventsStore.loading),
      error: computed(() => eventsStore.error),
      upcomingEvents: computed(() => eventsStore.upcomingEvents || []),
      pastEvents: computed(() => eventsStore.pastEvents || []),
      registeredEvents: computed(() => eventsStore.registeredEvents || []),
      pendingRegistrations: computed(() => eventsStore.pendingRegistrations || []),
      userRegistrations: computed(() => eventsStore.userRegistrations || []),
      activeTab,
      typeFilter,
      showRegistrationModal,
      selectedEvent,
      registrationNotes,
      registering,
      availabilityCheck,
      showSuccessNotification,
      filteredUpcomingEvents,
      loadEventsData,
      refreshEvents,
      applyFilters,
      handleRegister,
      confirmRegistration,
      handleCancelRegistration,
      viewEventDetails,
      closeRegistrationModal,
      formatDate
    }
  }
}
</script>

<style scoped>
/* Стили остаются без изменений */
.events-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 1rem;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 2rem;
}

.events-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  flex-wrap: wrap;
  gap: 1rem;
}

.tabs {
  display: flex;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 0.25rem;
  gap: 0.25rem;
}

.tab-button {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  background: transparent;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.tab-button.active {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  color: #2e8b57;
}

.tab-button:hover:not(.active) {
  background: rgba(255, 255, 255, 0.5);
}

.filters select {
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 8px;
  background: white;
  min-width: 150px;
}

.events-content {
  min-height: 400px;
}

.events-section {
  margin-bottom: 2rem;
}

.events-section h2 {
  margin-bottom: 1.5rem;
  color: #333;
}

.events-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 1.5rem;
}

.registrations-section {
  margin-bottom: 2rem;
}

.registrations-section h3 {
  margin-bottom: 1rem;
  color: #555;
}

.registrations-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.empty-state {
  text-align: center;
  padding: 3rem;
  background: #f8f9fa;
  border-radius: 12px;
  color: #666;
}

.empty-state p {
  margin-bottom: 1rem;
  font-size: 1.1rem;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  padding: 2rem;
  border-radius: 15px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.modal-header h3 {
  margin: 0;
}

.btn-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.btn-close:hover {
  background: #f8f9fa;
  color: #333;
}

.event-preview {
  background: #f8f9fa;
  padding: 1rem;
  border-radius: 8px;
  margin-bottom: 1.5rem;
  border-left: 4px solid #2e8b57;
}

.event-preview h4 {
  margin: 0 0 0.5rem;
  color: #333;
}

.event-details {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  margin: 1rem 0;
}

.detail {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #666;
}

.detail .icon {
  font-size: 1rem;
}

.availability-info {
  margin: 1rem 0;
  padding: 0.75rem;
  border-radius: 8px;
  font-weight: 500;
}

.availability-info .available {
  color: #155724;
  background: #d4edda;
  padding: 0.5rem;
  border-radius: 6px;
}

.availability-info .not-available {
  color: #721c24;
  background: #f8d7da;
  padding: 0.5rem;
  border-radius: 6px;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #333;
}

.form-group textarea {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-family: inherit;
  resize: vertical;
}

.form-group textarea:focus {
  outline: none;
  border-color: #2e8b57;
  box-shadow: 0 0 0 2px rgba(46, 139, 87, 0.2);
}

.char-count {
  text-align: right;
  font-size: 0.8rem;
  color: #666;
  margin-top: 0.25rem;
}

.form-info {
  background: #e7f3ff;
  padding: 0.75rem;
  border-radius: 8px;
  margin-bottom: 1.5rem;
  font-size: 0.9rem;
  color: #004085;
}

.form-info p {
  margin: 0;
}

.modal-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.notification {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1001;
  animation: slideIn 0.3s ease;
}

.notification.success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.notification-content {
  padding: 1rem 1.5rem;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 1rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.btn-retry {
  background: #2e8b57;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 6px;
  cursor: pointer;
  margin-left: 1rem;
}

.btn-retry:hover {
  background: #26734d;
}

/* Адаптивность */
@media (max-width: 768px) {
  .events-controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .tabs {
    order: 2;
  }
  
  .filters {
    order: 1;
    align-self: flex-end;
  }
  
  .events-grid {
    grid-template-columns: 1fr;
  }
  
  .modal-content {
    width: 95%;
    padding: 1rem;
  }
  
  .modal-actions {
    flex-direction: column;
  }
  
  .notification {
    left: 20px;
    right: 20px;
    top: 10px;
  }
  
  .notification-content {
    padding: 0.75rem 1rem;
  }
}
</style>