import { useEffect, useRef } from "react";
import QuickPinchZoom from "react-quick-pinch-zoom";

function drawToCanvas(canvas, imageData) {
  if (!canvas || !imageData) return;
  const context = canvas.getContext("2d");
  const image = new Image();
  image.onload = () => {
    canvas.width = image.naturalWidth;
    canvas.height = image.naturalHeight;
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(image, 0, 0);
  };
  image.src = imageData;
}

export default function CanvasPane({ title, imageData, histogram, transform, onTransform }) {
  const canvasRef = useRef(null);
  const holderRef = useRef(null);

  useEffect(() => {
    drawToCanvas(canvasRef.current, imageData);
  }, [imageData]);

  useEffect(() => {
    if (!holderRef.current) return;
    holderRef.current.style.transform = `translate3d(${transform.x}px, ${transform.y}px, 0) scale(${transform.scale})`;
  }, [transform]);

  return (
    <section className="flex min-h-full flex-1 flex-col overflow-hidden border border-zinc-800 bg-zinc-950">
      <div className="flex items-center justify-between border-b border-zinc-800 px-4 py-3">
        <h2 className="text-sm font-semibold text-zinc-100">{title}</h2>
        <span className="text-xs tabular-nums text-zinc-400">{histogram ? "p(r_k) ready" : "No histogram"}</span>
      </div>
      <div className="studio-grid flex min-h-[280px] flex-1 items-center justify-center overflow-hidden bg-zinc-950">
        {imageData ? (
          <QuickPinchZoom onUpdate={onTransform} inertia={false} wheelScaleFactor={180}>
            <div ref={holderRef} className="origin-top-left will-change-transform">
              <canvas ref={canvasRef} className="block max-h-[68vh] max-w-full shadow-2xl shadow-black/40" />
            </div>
          </QuickPinchZoom>
        ) : (
          <div className="px-6 text-center text-sm text-zinc-500">Upload an image to start processing.</div>
        )}
      </div>
    </section>
  );
}

export function CanvasThumbnail({ title, imageData }) {
  const canvasRef = useRef(null);

  useEffect(() => {
    drawToCanvas(canvasRef.current, imageData);
  }, [imageData]);

  if (!imageData) return null;

  return (
    <div className="absolute left-4 top-4 z-10 w-40 border border-zinc-700 bg-zinc-950/95 shadow-2xl shadow-black/50 md:w-52">
      <div className="border-b border-zinc-800 px-3 py-2 text-xs font-semibold text-zinc-100">{title}</div>
      <div className="max-h-40 overflow-hidden bg-black md:max-h-52">
        <canvas ref={canvasRef} className="block h-auto w-full" />
      </div>
    </div>
  );
}
