import { ref, onMounted, onUnmounted } from 'vue'

export function useWebSocket(url: string) {
  const ws = ref<WebSocket | null>(null)
  const isConnected = ref(false)
  const messages = ref<string[]>([])
  const error = ref<string | null>(null)

  const connect = () => {
    try {
      ws.value = new WebSocket(url)

      ws.value.onopen = () => {
        isConnected.value = true
        error.value = null
        console.log('WebSocket connected to:', url)
      }

      ws.value.onmessage = (event) => {
        console.log('Received message:', event.data)
        messages.value.push(event.data)
      }

      ws.value.onerror = (event) => {
        error.value = 'WebSocket error occurred'
        console.error('WebSocket error:', event)
      }

      ws.value.onclose = () => {
        isConnected.value = false
        console.log('WebSocket disconnected')
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : 'Failed to connect'
      console.error('Connection error:', err)
    }
  }

  const disconnect = () => {
    if (ws.value) {
      ws.value.close()
      ws.value = null
    }
  }

  const sendMessage = (message: string) => {
    if (ws.value && isConnected.value) {
      ws.value.send(message)
      console.log('Sent message:', message)
    } else {
      console.warn('WebSocket is not connected')
    }
  }

  onMounted(() => {
    connect()
  })

  onUnmounted(() => {
    disconnect()
  })

  return {
    isConnected,
    messages,
    error,
    connect,
    disconnect,
    sendMessage
  }
}
