import { ensure } from "@workshop/shared/utils"
import { useAction, Form, type Head } from "@workshop/nano-remix"
import { useEffect, useRef, useState } from "hono/jsx"
import { getGeminiResponse } from "../ai"
import result from "../result.json"
import { detectShapes } from "../opencv"

const categories = [
  "hand drawn circle",
  "hand drawn square",
  "hand drawn arrow",
  "hand drawn triangle",
  "hand drawn rectangle",
  "hand drawn polygon",
]
const prompts = {
  default: `Detect all of the of the following objects: ${categories}. The box_2d should be an object with ymin, xmin, ymax, xmax properties normalized to 0-1000.`,
  simple: `Detect the 2d bounding boxes of the following objects: ${categories}.`,
  specific: `Detect 2d bounding box for the tea kettle in the image. The box_2d should be an object with ymin, xmin, ymax, xmax properties normalized to 0-1000.`,
}

export const action = async (req: Request, params: {}) => {
  const imageBuffer = await Bun.file("public/whiteboard.png").arrayBuffer()
  const response = await getGeminiResponse(imageBuffer, prompts.specific)
  // return { elements: response?.elements || [] }

  // const response = await detectShapes(imageBuffer)
  return { elements: response!.elements }
}

export default function Index() {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const [image, setImage] = useState<HTMLImageElement | null>(null)
  const { data, error, loading } = useAction<typeof action>()

  useEffect(() => {
    const img = new Image()

    img.onload = () => {
      setImage(img)
      ensure(canvasRef.current, "Canvas ref must be set before loading image")
      canvasRef.current.width = img.width
      canvasRef.current.height = img.height
    }

    img.src = "/whiteboard.png"
  }, [])

  useEffect(() => {
    const canvas = canvasRef.current
    const ctx = canvas?.getContext("2d")

    if (!image) return
    ensure(canvas, "Canvas ref must be set before drawing")
    ensure(ctx, "Canvas context must be available before drawing")

    ctx.clearRect(0, 0, canvas.width, canvas.height)
    ctx.drawImage(image, 0, 0)

    // Draw AI detected elements with box_2d format
    data?.elements.forEach((element, index) => {
      const { ymin, xmin, ymax, xmax } = element

      // Convert normalized coordinates (0-1000) to actual canvas coordinates
      const x = (xmin / 1000) * canvas.width
      const y = (ymin / 1000) * canvas.height
      const width = ((xmax - xmin) / 1000) * canvas.width
      const height = ((ymax - ymin) / 1000) * canvas.height

      // Draw bounding box
      ctx.strokeStyle = "#ff00ff" // Magenta for AI detections
      ctx.lineWidth = 3
      ctx.strokeRect(x, y, width, height) // Draw label
      ctx.fillStyle = "#ff00ff"
      ctx.font = "14px Arial"
      ctx.fillText(`${element.label}`, x, y - 5)
    })
  }, [image, data?.elements])

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

      <Form name="analyzeWhiteboard">
        <button
          type="submit"
          class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition-colors"
        >
          Analyze Whiteboard
        </button>
      </Form>

      <div class="mb-4">
        <h2 class="text-xl font-semibold mb-2">AI Analysis: {loading ? "Loading..." : ""}</h2>
        <p class="mb-2">
          <strong>Detected Elements:</strong> {data?.elements.length}
        </p>
      </div>

      <div class="border-2 border-gray-300 inline-block">
        <canvas ref={canvasRef} class="max-w-full h-auto" />
        <ul class="list-disc list-inside mb-4">
          {data?.elements.map((element, index) => (
            <li key={index}>
              {element.label} at box_2d: [{element.ymin}, {element.xmin}, {element.ymax}, {element.xmax}]
            </li>
          ))}
        </ul>
      </div>
    </div>
  )
}
