// stores/events.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { apiClient, withLoading } from './helpers/api'

export const useEventsStore = defineStore('events', () => {
  // State
  const events = ref([])
  const userRegistrations = ref([])
  const eventDetails = ref(null)
  const loading = ref(false)
  const error = ref('')

  // Getters - добавляем проверки на null/undefined
  const upcomingEvents = computed(() => {
    if (!events.value || !Array.isArray(events.value)) return []
    return events.value
      .filter(event => event && new Date(event.date) > new Date())
      .sort((a, b) => new Date(a.date) - new Date(b.date))
  })

  const pastEvents = computed(() => {
    if (!events.value || !Array.isArray(events.value)) return []
    return events.value
      .filter(event => event && new Date(event.date) <= new Date())
      .sort((a, b) => new Date(b.date) - new Date(a.date))
  })

  const registeredEvents = computed(() => {
    if (!userRegistrations.value || !Array.isArray(userRegistrations.value)) return []
    return userRegistrations.value
      .filter(reg => reg && reg.status === 'confirmed')
      .map(reg => ({
        ...reg.event,
        registration_status: reg.status,
        registration_id: reg.id,
        result_time: reg.result_time
      }))
  })

  const pendingRegistrations = computed(() => {
    if (!userRegistrations.value || !Array.isArray(userRegistrations.value)) return []
    return userRegistrations.value.filter(reg => reg && reg.status === 'pending')
  })

  const eventTypes = {
    'race': 'Забег',
    'training': 'Тренировка',
    'social': 'Встреча',
    'workshop': 'Семинар'
  }

  // Actions
  const fetchEvents = async (params = {}) => {
    return withLoading({ loading, error }, async () => {
      try {
        const queryString = new URLSearchParams(params).toString()
        const response = await apiClient.get(`/events?${queryString}`)
        events.value = response.data || []
        return { success: true, data: events.value }
      } catch (error) {
        console.warn('Events endpoint not available, using mock data', error)
        events.value = generateMockEvents()
        return { success: true, data: events.value }
      }
    })
  }

  const fetchUpcomingEvents = async () => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.get('/events/upcoming')
        events.value = response.data || []
        return { success: true, data: events.value }
      } catch (error) {
        console.warn('Upcoming events endpoint not available' + 'error = ' + error)
        return { success: true, data: upcomingEvents.value }
      }
    })
  }

  const fetchEventDetails = async (eventId) => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.get(`/events/${eventId}`)
        eventDetails.value = response.data
        return { success: true, data: response.data }
      } catch (error) {
        console.warn('Event details endpoint not available' + 'error = ' + error)
        eventDetails.value = events.value.find(event => event && event.id === parseInt(eventId)) || null
        return { success: true, data: eventDetails.value }
      }
    })
  }

  const fetchUserRegistrations = async () => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.get('/events/my/registrations')
        userRegistrations.value = response.data || []
        return { success: true, data: userRegistrations.value }
      } catch (error) {
        console.warn('User registrations endpoint not available, using mock data', error)
        userRegistrations.value = generateMockRegistrations()
        return { success: true, data: userRegistrations.value }
      }
    })
  }

  const registerForEvent = async (eventId, notes = '') => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.post('/events/register', {
          event_id: eventId,
          notes: notes
        })
        
        // Обновляем список регистраций
        await fetchUserRegistrations()
        return { success: true, data: response.data }
      } catch (error) {
        return { success: false, error: error.message }
      }
    })
  }

  const cancelRegistration = async (registrationId) => {
    return withLoading({ loading, error }, async () => {
      try {
        await apiClient.delete(`/events/registrations/${registrationId}`)
        
        // Обновляем список регистраций
        await fetchUserRegistrations()
        return { success: true }
      } catch (error) {
        return { success: false, error: error.message }
      }
    })
  }

  const checkEventAvailability = async (eventId) => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.get(`/events/${eventId}/availability`)
        return { success: true, data: response.data }
      } catch (error) {
        console.warn('Event availability endpoint not available' + 'error = ' + error)
        const event = events.value.find(e => e && e.id === parseInt(eventId))
        const available = event && 
          event.registration_open && 
          (event.max_participants === 0 || event.participants_count < event.max_participants)
        return { success: true, data: { 
          available, 
          remaining_spots: event ? event.max_participants - event.participants_count : 0 
        } }
      }
    })
  }

  const createEvent = async (eventData) => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.post('/events', eventData)
        events.value.push(response.data)
        return { success: true, data: response.data }
      } catch (error) {
        return { success: false, error: error.message }
      }
    })
  }

  const updateEvent = async (eventId, eventData) => {
    return withLoading({ loading, error }, async () => {
      try {
        const response = await apiClient.put(`/events/${eventId}`, eventData)
        const index = events.value.findIndex(event => event && event.id === parseInt(eventId))
        if (index !== -1) {
          events.value[index] = response.data
        }
        return { success: true, data: response.data }
      } catch (error) {
        return { success: false, error: error.message }
      }
    })
  }

  // Вспомогательные функции для mock данных
  const generateMockEvents = () => {
    return [
      {
        id: 1,
        title: 'Весенний марафон 2024',
        description: 'Ежегодный весенний марафон по живописному маршруту через городской парк и набережную. Дистанции: 5км, 10км, полумарафон.',
        date: '2024-04-15T09:00:00',
        location: 'Городской парк, Центральный вход',
        type: 'race',
        distance: '5км, 10км, 21.1км',
        participants_count: 45,
        max_participants: 100,
        registration_open: true,
        image: '/images/spring-marathon.jpg',
        created_at: '2024-01-15T10:00:00'
      },
      {
        id: 2,
        title: 'Тренировка для начинающих',
        description: 'Групповая тренировка для тех, кто только начинает бегать. Основы техники, дыхания и планирования тренировок.',
        date: '2024-03-20T18:30:00',
        location: 'Стадион "Спартак"',
        type: 'training',
        distance: '',
        participants_count: 12,
        max_participants: 20,
        registration_open: true,
        image: '/images/beginner-training.jpg',
        created_at: '2024-02-01T14:30:00'
      },
      {
        id: 3,
        title: 'Встреча бегового клуба',
        description: 'Ежемесячная встреча участников бегового клуба. Обсуждение планов, обмен опытом, совместная пробежка.',
        date: '2024-03-25T19:00:00',
        location: 'Кафе "Бегун"',
        type: 'social',
        distance: '',
        participants_count: 8,
        max_participants: 0,
        registration_open: true,
        image: '/images/running-club.jpg',
        created_at: '2024-02-10T11:20:00'
      },
      {
        id: 4,
        title: 'Семинар по питанию для бегунов',
        description: 'Эксперт расскажет о правильном питании до, во время и после тренировок и соревнований.',
        date: '2024-04-05T17:00:00',
        location: 'Фитнес-центр "Актив"',
        type: 'workshop',
        distance: '',
        participants_count: 25,
        max_participants: 30,
        registration_open: true,
        image: '/images/nutrition-workshop.jpg',
        created_at: '2024-01-20T16:45:00'
      }
    ]
  }

  const generateMockRegistrations = () => {
    return [
      {
        id: 1,
        user_id: 1,
        event_id: 1,
        status: 'confirmed',
        notes: 'Участвую в полумарафоне',
        result_time: '',
        created_at: '2024-02-15T10:00:00',
        event: {
          id: 1,
          title: 'Весенний марафон 2024',
          date: '2024-04-15T09:00:00',
          location: 'Городской парк'
        }
      },
      {
        id: 2,
        user_id: 1,
        event_id: 2,
        status: 'pending',
        notes: '',
        result_time: '',
        created_at: '2024-03-01T14:20:00',
        event: {
          id: 2,
          title: 'Тренировка для начинающих',
          date: '2024-03-20T18:30:00',
          location: 'Стадион "Спартак"'
        }
      }
    ]
  }

  const resetEventsStore = () => {
    events.value = []
    userRegistrations.value = []
    eventDetails.value = null
    loading.value = false
    error.value = ''
  }

  return {
    // State
    events,
    userRegistrations,
    eventDetails,
    loading,
    error,

    // Getters
    upcomingEvents,
    pastEvents,
    registeredEvents,
    pendingRegistrations,
    eventTypes,

    // Actions
    fetchEvents,
    fetchUpcomingEvents,
    fetchEventDetails,
    fetchUserRegistrations,
    registerForEvent,
    cancelRegistration,
    checkEventAvailability,
    createEvent,
    updateEvent,
    resetEventsStore
  }
})