"use client";

import { useEffect, useImperativeHandle, useRef, forwardRef } from "react";

export interface SignaturePadHandle {
  isSigned: () => boolean;
  clear: () => void;
  toDataURL: () => string;
  getDimensions: () => { width: number; height: number };
}

interface Props {
  width?: number;
  height?: number;
  className?: string;
}

// approvalDetailResultPopup.jsp 의 signCanvas 대응 - 터치/마우스 서명 캔버스
export const SignaturePad = forwardRef<SignaturePadHandle, Props>(function SignaturePad(
  { width = 480, height = 140, className },
  ref
) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const signedRef = useRef(false);

  useImperativeHandle(ref, () => ({
    isSigned: () => signedRef.current,
    clear: () => {
      const c = canvasRef.current;
      if (!c) return;
      const ctx = c.getContext("2d");
      if (!ctx) return;
      ctx.clearRect(0, 0, c.width, c.height);
      signedRef.current = false;
    },
    toDataURL: () => canvasRef.current?.toDataURL("image/png") || "",
    getDimensions: () => ({
      width: canvasRef.current?.width || width,
      height: canvasRef.current?.height || height,
    }),
  }));

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;
    ctx.lineWidth = 2;
    ctx.lineCap = "round";
    ctx.strokeStyle = "#111";

    let drawing = false;
    let lastX = 0;
    let lastY = 0;

    const getPos = (e: MouseEvent | TouchEvent) => {
      const rect = canvas.getBoundingClientRect();
      if (e instanceof MouseEvent) {
        return { x: e.clientX - rect.left, y: e.clientY - rect.top };
      }
      const t = e.touches[0];
      return { x: t.clientX - rect.left, y: t.clientY - rect.top };
    };

    const start = (e: MouseEvent | TouchEvent) => {
      e.preventDefault();
      drawing = true;
      signedRef.current = true;
      const { x, y } = getPos(e);
      lastX = x; lastY = y;
    };
    const move = (e: MouseEvent | TouchEvent) => {
      if (!drawing) return;
      e.preventDefault();
      const { x, y } = getPos(e);
      ctx.beginPath();
      ctx.moveTo(lastX, lastY);
      ctx.lineTo(x, y);
      ctx.stroke();
      lastX = x; lastY = y;
    };
    const end = () => { drawing = false; };

    canvas.addEventListener("mousedown", start);
    canvas.addEventListener("mousemove", move);
    canvas.addEventListener("mouseup", end);
    canvas.addEventListener("mouseleave", end);
    canvas.addEventListener("touchstart", start, { passive: false });
    canvas.addEventListener("touchmove", move, { passive: false });
    canvas.addEventListener("touchend", end);
    canvas.addEventListener("touchcancel", end);

    return () => {
      canvas.removeEventListener("mousedown", start);
      canvas.removeEventListener("mousemove", move);
      canvas.removeEventListener("mouseup", end);
      canvas.removeEventListener("mouseleave", end);
      canvas.removeEventListener("touchstart", start);
      canvas.removeEventListener("touchmove", move);
      canvas.removeEventListener("touchend", end);
      canvas.removeEventListener("touchcancel", end);
    };
  }, []);

  return (
    <canvas
      ref={canvasRef}
      width={width}
      height={height}
      className={`border border-gray-400 bg-white cursor-crosshair touch-none ${className || ""}`}
    />
  );
});
