import { useRef, useState, useEffect } from "hono/jsx"
import { useStreamingAI } from "../useStreamingAI"
import { useVideo } from "../useVideo"
import { VideoOverlay } from "../videoOverlay"
import "../index.css"
import type { OverlayItem } from "../types"

export default function Voice() {
  const {
    audioError,
    transcript,
    isRecording: audioRecording,
    waitingForResponse,
    overlays,
  } = useStreamingAI()
  const videoRef = useRef<HTMLVideoElement>(null)
  const video = useVideo(videoRef)

  let recordingStateClass = ""
  if (audioRecording) recordingStateClass = "border-red-500 border-4"
  else if (waitingForResponse) recordingStateClass = "border-yellow-500 border-4"

  return (
    <div class="p-8 h-dvh w-full flex flex-col justify-center align-middle">
      {audioError && <p class="text-red-500">Audio Error: {audioError}</p>}
      {video.error && <p class="text-red-500">Video Error: {video.error}</p>}

      {!video.isRecording && (
        <button
          onClick={video.toggleRecording}
          class="px-4 uppercase py-2 text-8xl rounded-2xl text-white bg-green-500 hover:bg-green-600"
        >
          Start THE Camera
        </button>
      )}

      <VideoOverlay overlays={overlays} isRecording={video.isRecording}>
        <video
          ref={videoRef}
          autoPlay
          muted
          playsInline
          class={`w-full h-full object-cover transition-all duration-300 ${recordingStateClass}`}
        />
      </VideoOverlay>
      {video.isRecording && <div class="text-sm italic text-center">Hold Space to ask a question</div>}

      {transcript && <div class="absolute top-5 left-5 right-5 bg-white/90 p-4 rounded-lg">{transcript}</div>}
    </div>
  )
}
