import { useRef, useState, useEffect } from "hono/jsx"
import { useAction, submitAction } from "@workshop/nano-remix"
import { join } from "path"
import { useVideo } from "../useVideo"
import { VideoOverlay, type OverlayItem } from "../videoOverlay"
import "../index.css"

export const action = async (req: Request, params: {}) => {
  const formData = await req.formData()
  const imageData = formData.get("imageData") as string

  if (!imageData) {
    return { success: false, error: "No image provided" }
  }

  const filename = `whiteboard.png`
  const base64Data = imageData.split(",")[1]
  if (!base64Data) {
    return { success: false, error: "Invalid image data" }
  }

  const buffer = Buffer.from(base64Data, "base64")
  const publicPath = join(import.meta.dir, `../../public/${filename}`)

  try {
    await Bun.write(publicPath, buffer)
    return { success: true, filename, path: publicPath }
  } catch (error) {
    return { success: false, error: "Failed to save image" }
  }
}

export default function Camera() {
  const videoRef = useRef<HTMLVideoElement>(null)
  const { data, error: uploadError, loading } = useAction<typeof action>()
  const [overlays, setOverlays] = useState<OverlayItem[]>([
    {
      type: "text",
      x: 50,
      y: 50,
      text: "Camera Feed",
      fontSize: 24,
      color: "yellow",
      strokeColor: "black",
    },
    {
      type: "image",
      x: 100,
      y: 100,
      src: "https://picsum.photos/seed/wow/200/300",
    },
  ])

  const { isRecording, error, toggleRecording } = useVideo(videoRef, {
    onCapture: (dataURL) => {
      const formData = new FormData()
      formData.append("imageData", dataURL)
      submitAction(formData)
    },
  })

  // Update overlays when camera state changes
  useEffect(() => {}, [isRecording])

  return (
    <div class="p-5">
      <h1 class="text-3xl font-bold mb-5">Camera Test</h1>

      {error && (
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">{error}</div>
      )}

      <div class="mb-4">
        <button
          onClick={toggleRecording}
          class={`px-4 py-2 rounded text-white ${
            isRecording ? "bg-red-500 hover:bg-red-600" : "bg-green-500 hover:bg-green-600"
          }`}
        >
          {isRecording ? "Stop Camera" : "Start Camera"}
        </button>
      </div>

      {uploadError && (
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">{uploadError}</div>
      )}

      <VideoOverlay overlays={overlays} isRecording={isRecording}>
        <video ref={videoRef} autoPlay muted playsInline class="w-full max-w-lg object-cover" />
      </VideoOverlay>

      <script src="https://cdn.jsdelivr.net/npm/eruda"></script>
      <script>eruda.init()</script>
    </div>
  )
}
