import { useEffect, useRef, useState } from "hono/jsx"
import { StreamingResponse } from "./streamingAI"
import type { OverlayItem } from "./types"

export function useStreamingAI() {
  const [audioError, setAudioError] = useState<string>("")
  const [transcript, setTranscript] = useState<string>("")
  const [isRecording, setIsRecording] = useState(false)
  const [waitingForResponse, setWaitingForResponse] = useState(false)
  const [overlays, setOverlays] = useState<OverlayItem[]>([])
  const streamingResponseRef = useRef<StreamingResponse>(null)

  const startRecording = async () => {
    setAudioError("")
    setTranscript("")
    streamingResponseRef.current = new StreamingResponse((error) => setAudioError(error))
    await streamingResponseRef.current.start()
    setIsRecording(true)
  }

  const endRecording = async () => {
    setIsRecording(false)
    try {
      setWaitingForResponse(true)
      const reader = await streamingResponseRef.current!.stop()
      setWaitingForResponse(false)
      const decoder = new TextDecoder()
      let buffer = ""

      const overlayItems: OverlayItem[] = []
      while (true) {
        const { done, value } = await reader.read()
        if (done) break

        const chunk = decoder.decode(value, { stream: true })
        buffer += chunk

        // Parse SSE messages
        const lines = buffer.split("\n")
        buffer = lines.pop() || ""

        for (const line of lines) {
          if (line.startsWith("data: ")) {
            try {
              const eventData = JSON.parse(line.slice(6))

              if (eventData.type === "text_delta") {
                setTranscript((prev) => prev + eventData.data)
              } else if (eventData.type === "tool_output") {
                if (eventData.data.type === "image") {
                  overlayItems.push(eventData.data)
                }
              } else if (eventData.type === "done") {
                console.log("Done")
              }
            } catch (e) {
              console.error("💥 Failed to parse SSE event:", line, e)
            }
          } else if (line.trim()) {
            console.error("💥 Non-data line:", line)
          }
        }
      }

      setOverlays(overlayItems)
    } catch (error) {
      console.error("Error during streaming:", error)
      setAudioError(`Streaming failed: ${error}`)
    } finally {
      setWaitingForResponse(false)
    }
  }

  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.code === "Space" && !event.repeat && !isRecording) {
        event.preventDefault()
        startRecording()
      }
    }

    const handleKeyUp = (event: KeyboardEvent) => {
      if (event.code === "Space" && isRecording) {
        event.preventDefault()
        endRecording()
      }
    }

    window.addEventListener("keydown", handleKeyDown)
    window.addEventListener("keyup", handleKeyUp)

    return () => {
      window.removeEventListener("keydown", handleKeyDown)
      window.removeEventListener("keyup", handleKeyUp)
    }
  }, [isRecording])

  return {
    audioError,
    transcript,
    isRecording,
    waitingForResponse,
    startRecording,
    endRecording,
    overlays,
  }
}
