import { useEffect, useMemo, useRef, useState } from "react";
import { Button } from "@/components/ui/button";

const CANVAS_WIDTH = 900;
const CANVAS_HEIGHT = 220;

function getTokenColor(variableName, fallback) {
  if (typeof window === "undefined") return fallback;

  const value = getComputedStyle(document.documentElement)
    .getPropertyValue(variableName)
    .trim();

  return value ? `hsl(${value})` : fallback;
}

export default function PublicFormSignatureField({ value, onChange, disabled = false }) {
  const canvasRef = useRef(null);
  const [isDrawing, setIsDrawing] = useState(false);
  const [hasDrawn, setHasDrawn] = useState(Boolean(value));

  const colors = useMemo(
    () => ({
      stroke: getTokenColor("--foreground", "#111827"),
      fill: getTokenColor("--background", "#ffffff"),
    }),
    []
  );

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const context = canvas.getContext("2d");
    context.fillStyle = colors.fill;
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.lineCap = "round";
    context.lineJoin = "round";
    context.lineWidth = 3;
    context.strokeStyle = colors.stroke;

    if (!value) {
      setHasDrawn(false);
      return;
    }

    const image = new Image();
    image.onload = () => {
      context.fillStyle = colors.fill;
      context.fillRect(0, 0, canvas.width, canvas.height);
      context.drawImage(image, 0, 0, canvas.width, canvas.height);
      setHasDrawn(true);
    };
    image.src = value;
  }, [colors.fill, colors.stroke, value]);

  const getPosition = (event) => {
    const canvas = canvasRef.current;
    const rect = canvas.getBoundingClientRect();
    const scaleX = canvas.width / rect.width;
    const scaleY = canvas.height / rect.height;
    const point = "touches" in event ? event.touches[0] : event;

    return {
      x: (point.clientX - rect.left) * scaleX,
      y: (point.clientY - rect.top) * scaleY,
    };
  };

  const startDrawing = (event) => {
    if (disabled) return;

    event.preventDefault();
    const canvas = canvasRef.current;
    const context = canvas.getContext("2d");
    const position = getPosition(event);

    context.beginPath();
    context.moveTo(position.x, position.y);
    setIsDrawing(true);
  };

  const draw = (event) => {
    if (!isDrawing || disabled) return;

    event.preventDefault();
    const canvas = canvasRef.current;
    const context = canvas.getContext("2d");
    const position = getPosition(event);

    context.lineTo(position.x, position.y);
    context.stroke();
  };

  const stopDrawing = () => {
    if (!isDrawing) return;

    setIsDrawing(false);
    setHasDrawn(true);
    onChange?.(canvasRef.current?.toDataURL("image/png") || "");
  };

  const clearSignature = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const context = canvas.getContext("2d");
    context.fillStyle = colors.fill;
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.beginPath();
    setHasDrawn(false);
    onChange?.("");
  };

  return (
    <div className="space-y-3">
      <div className="rounded-lg border border-border bg-background p-2">
        <canvas
          ref={canvasRef}
          width={CANVAS_WIDTH}
          height={CANVAS_HEIGHT}
          onPointerDown={startDrawing}
          onPointerMove={draw}
          onPointerUp={stopDrawing}
          onPointerLeave={stopDrawing}
          className="h-40 w-full cursor-crosshair rounded-md bg-background touch-none"
        />
      </div>

      <div className="flex items-center justify-between gap-3 text-xs text-muted-foreground">
        <span>{hasDrawn ? "Signature captured." : "Draw your signature in the box above."}</span>
        <Button type="button" variant="outline" size="sm" onClick={clearSignature} disabled={disabled || !hasDrawn}>
          Clear
        </Button>
      </div>
    </div>
  );
}
