import { ref } from 'vue'
import { defineStore } from 'pinia'
import { activityService } from '@/services/activityService'
import { API_BASE_URL } from '@/config/api-config'
import type { Activity } from '@/types/activity'

export const useActivityStore = defineStore('activity', () => {
    const activities = ref<Activity[]>([])
    const isLoading = ref(false)
    const error = ref<string | null>(null)
    const cursor = ref<number | null>(null)
    const hasMore = ref(true)
    const currentGroupId = ref<number | null>(null)
    const socket = ref<WebSocket | null>(null)

    async function fetchActivities(groupId: number, limit: number = 20) {
        if (isLoading.value || !hasMore.value) return;

        isLoading.value = true
        error.value = null

        if (groupId !== currentGroupId.value) {
            // Reset if group changes
            activities.value = []
            cursor.value = null
            hasMore.value = true
        }
        currentGroupId.value = groupId

        try {
            const response = await activityService.getGroupActivity(groupId, limit, cursor.value)
            activities.value.push(...response.items)
            cursor.value = response.cursor
            if (!response.cursor || response.items.length < limit) {
                hasMore.value = false
            }
        } catch (e: any) {
            error.value = e.message || 'Failed to fetch activities'
        } finally {
            isLoading.value = false
        }
    }

    function connectWebSocket(groupId: number, token: string | null) {
        if (socket.value) {
            socket.value.close()
        }
        const base = import.meta.env.DEV ? `ws://${location.host}/ws/${groupId}` : `${API_BASE_URL.replace('https', 'wss').replace('http', 'ws')}/ws/${groupId}`
        const url = token ? `${base}?token=${token}` : base

        socket.value = new WebSocket(url)
        socket.value.onopen = () => {
            console.debug('[WS] Connected to', url)
        }

        // Handle incoming messages
        socket.value.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data)
                if (data.event === 'activity:new' && data.payload?.activity) {
                    const newAct: Activity = data.payload.activity
                    // Avoid duplicates
                    if (!activities.value.some(a => a.id === newAct.id)) {
                        activities.value.unshift(newAct)
                    }
                } else if (data.event === 'activity:deleted' && data.payload?.id) {
                    activities.value = activities.value.filter(a => a.id !== data.payload.id)
                } else if (data.event === 'activity:updated' && data.payload?.activity) {
                    const idx = activities.value.findIndex(a => a.id === data.payload.activity.id)
                    if (idx >= 0) activities.value[idx] = data.payload.activity
                }
            } catch (err) {
                console.error('[WS] Failed to parse message', err)
            }
        }

        // Auto-reconnect on unexpected close
        socket.value.onclose = (evt) => {
            console.warn('[WS] Closed', evt.code, evt.reason)
            socket.value = null
            // 1000 = normal close
            if (evt.code !== 1000) {
                setTimeout(() => connectWebSocket(groupId, token), 2000)
            }
        }

        socket.value.onerror = (error) => {
            console.error('[WS] Error', error)
        }
    }

    function disconnectWebSocket() {
        if (socket.value) {
            socket.value.close()
            socket.value = null
        }
    }

    return {
        activities,
        isLoading,
        error,
        hasMore,
        fetchActivities,
        connectWebSocket,
        disconnectWebSocket,
    }
}) 