import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import {
  getRealtimeClient,
  type PgViewersData,
  type ListUpdateData,
} from '../composables/useRealtime'

export interface TaskProgress {
  taskId: string
  percent: number
  title?: string
  description?: string
  status: 'pending' | 'running' | 'success' | 'error'
  message?: string
}

export const useRealtimeStore = defineStore('realtime', () => {
  // Connection state
  const connected = ref(false)
  const connectionError = ref<string | null>(null)

  // Document viewers: key = "pagetype:pagename", value = array of usernames
  const documentViewers = ref<Map<string, string[]>>(new Map())

  // Task progress tracking
  const taskProgress = ref<Map<string, TaskProgress>>(new Map())

  // Pending list updates
  const pendingListUpdates = ref<Map<string, ListUpdateData>>(new Map())

  // Notification count
  const unreadNotifications = ref(0)

  // Has version update
  const hasVersionUpdate = ref(false)

  // Is initialized
  const initialized = ref(false)

  // Client reference
  let client: ReturnType<typeof getRealtimeClient> | null = null

  /**
   * Initialize realtime connection and global listeners
   */
  function init() {
    if (initialized.value) return

    client = getRealtimeClient()

    // Sync connection state using watch
    watch(() => client!.connected.value, (val) => {
      connected.value = val
    }, { immediate: true })
    watch(() => client!.connectionError.value, (val) => {
      connectionError.value = val
    }, { immediate: true })

    // Setup global event listeners
    setupGlobalListeners()

    initialized.value = true
  }

  /**
   * Setup global event listeners for common events
   */
  function setupGlobalListeners() {
    if (!client) return

    // Document viewers update
    client.on<PgViewersData>('pg_viewers', (data) => {
      const key = `${data.pagetype}:${data.pagename}`
      documentViewers.value.set(key, data.users)
    })

    // Version update notification
    client.on('version-update', () => {
      hasVersionUpdate.value = true
    })

    // Notification indicator
    client.on('notification', () => {
      unreadNotifications.value++
    })

    // List updates - debounced batch processing
    client.on<ListUpdateData>('list_update', (data) => {
      const key = `${data.pagetype}:${data.name}`
      pendingListUpdates.value.set(key, data)
    })
  }

  /**
   * Get viewers for a specific document
   */
  function getViewers(pagetype: string, pagename: string): string[] {
    const key = `${pagetype}:${pagename}`
    return documentViewers.value.get(key) || []
  }

  /**
   * Clear viewers for a document
   */
  function clearViewers(pagetype: string, pagename: string) {
    const key = `${pagetype}:${pagename}`
    documentViewers.value.delete(key)
  }

  /**
   * Update task progress
   */
  function updateTaskProgress(taskId: string, progress: Partial<TaskProgress>) {
    const existing = taskProgress.value.get(taskId) || {
      taskId,
      percent: 0,
      status: 'pending' as const,
    }
    taskProgress.value.set(taskId, { ...existing, ...progress })
  }

  /**
   * Clear task progress
   */
  function clearTaskProgress(taskId: string) {
    taskProgress.value.delete(taskId)
  }

  /**
   * Get pending list update
   */
  function consumeListUpdate(pagetype: string): ListUpdateData[] {
    const updates: ListUpdateData[] = []
    const keysToRemove: string[] = []

    pendingListUpdates.value.forEach((data, key) => {
      if (key.startsWith(`${pagetype}:`)) {
        updates.push(data)
        keysToRemove.push(key)
      }
    })

    keysToRemove.forEach((key) => pendingListUpdates.value.delete(key))
    return updates
  }

  /**
   * Clear notification count
   */
  function clearNotifications() {
    unreadNotifications.value = 0
  }

  /**
   * Reset version update flag
   */
  function dismissVersionUpdate() {
    hasVersionUpdate.value = false
  }

  /**
   * Disconnect and cleanup
   */
  function disconnect() {
    if (client) {
      client.disconnect()
    }
    documentViewers.value.clear()
    taskProgress.value.clear()
    pendingListUpdates.value.clear()
    initialized.value = false
  }

  return {
    // State
    connected,
    connectionError,
    documentViewers,
    taskProgress,
    pendingListUpdates,
    unreadNotifications,
    hasVersionUpdate,
    initialized,

    // Actions
    init,
    getViewers,
    clearViewers,
    updateTaskProgress,
    clearTaskProgress,
    consumeListUpdate,
    clearNotifications,
    dismissVersionUpdate,
    disconnect,
  }
})
