import { useState, useEffect, type RefObject } from "hono/jsx"
import { ensure } from "@workshop/shared/utils"

interface UseVideoOptions {
  captureInterval?: number
}

export function useVideo(videoRef: RefObject<HTMLVideoElement>, options: UseVideoOptions = {}) {
  const { captureInterval = 10000 } = options
  const [isRecording, setIsRecording] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const captureImage = () => {
    ensure(videoRef.current, "Video ref must be set before capturing image")

    const video = videoRef.current
    const canvas = document.createElement("canvas")

    const maxWidth = 1000
    const maxHeight = 1000
    const aspectRatio = video.videoWidth / video.videoHeight

    let newWidth = maxWidth
    let newHeight = maxHeight

    if (aspectRatio > 1) {
      newHeight = maxWidth / aspectRatio
    } else {
      newWidth = maxHeight * aspectRatio
    }

    canvas.width = newWidth
    canvas.height = newHeight

    const ctx = canvas.getContext("2d")
    if (!ctx) return

    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.drawImage(video, 0, 0, newWidth, newHeight)
    const dataURL = canvas.toDataURL("image/png")

    uploadImage(dataURL)

    return dataURL
  }

  const uploadImage = async (dataURL: string) => {
    const formData = new FormData()
    formData.append("imageData", dataURL)

    try {
      const response = await fetch("/upload", {
        method: "POST",
        body: formData,
      })
      const result = await response.json()
      console.log("Image uploaded:", result)
    } catch (error) {
      console.error("Upload failed:", error)
    }
  }

  const startCamera = async () => {
    try {
      const mediaStream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode: "environment" },
      })

      if (videoRef.current) {
        videoRef.current.srcObject = mediaStream
        videoRef.current.onloadedmetadata = () => {
          setTimeout(captureImage, 100)
        }
      }

      setIsRecording(true)
      setError(null)
    } catch (err) {
      setError("Failed to access camera")
      setIsRecording(false)
    }
  }

  const stopCamera = () => {
    if (!isRecording || !videoRef.current?.srcObject) return

    const stream = videoRef.current.srcObject as MediaStream
    stream.getTracks().forEach((track) => track.stop())

    if (videoRef.current) {
      videoRef.current.srcObject = null
    }

    setIsRecording(false)
  }

  const toggleRecording = () => {
    if (isRecording) {
      stopCamera()
    } else {
      startCamera()
    }
  }

  useEffect(() => {
    if (!isRecording) return

    const interval = setInterval(() => {
      captureImage()
    }, captureInterval)

    return () => clearInterval(interval)
  }, [isRecording, captureInterval])

  return {
    isRecording,
    error,
    toggleRecording,
  }
}
