import { useState, useEffect } from 'react'

export const useWebSocket = (
  url: string,
  onMessage: (event: MessageEvent) => void,
  onOpen?: () => void,
  onClose?: () => void
) => {
  const [socket, setSocket] = useState<WebSocket | null>(null)
  const [isConnected, setIsConnected] = useState(false)

  useEffect(() => {
    const ws = new WebSocket(url)

    ws.onopen = () => {
      setIsConnected(true)
      onOpen?.()
    }

    ws.onmessage = onMessage

    ws.onclose = () => {
      setIsConnected(false)
      onClose?.()
    }

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

    setSocket(ws)

    return () => {
      ws.close()
    }
  }, [url])

  const send = (data: unknown) => {
    if (socket && socket.readyState === WebSocket.OPEN) {
      socket.send(JSON.stringify(data))
    }
  }

  return { socket, isConnected, send }
}
