import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react';

const SignatureCanvas = forwardRef(function SignatureCanvas(
  { value, onChange, onClear, variant = 'default', hideActions = false, watermark = '' },
  ref,
) {
  const canvasRef = useRef(null);
  const wrapRef = useRef(null);
  const drawing = useRef(false);
  const [hasStroke, setHasStroke] = useState(!!value);
  const isEsign = variant === 'esign';
  const isFullscreen = variant === 'fullscreen' || isEsign;

  const valueRef = useRef(value);
  valueRef.current = value;

  const setupCanvas = useCallback(() => {
    const canvas = canvasRef.current;
    const wrap = wrapRef.current;
    if (!canvas || !wrap) return;

    const rect = wrap.getBoundingClientRect();
    if (rect.width <= 0 || rect.height <= 0) return;

    const savedValue = valueRef.current;
    canvas.width = rect.width * 2;
    canvas.height = rect.height * 2;
    const ctx = canvas.getContext('2d');
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.scale(2, 2);
    ctx.strokeStyle = '#1D2129';
    ctx.lineWidth = isEsign ? 3 : isFullscreen ? 2.5 : 2;
    ctx.lineCap = 'round';
    ctx.lineJoin = 'round';
    ctx.clearRect(0, 0, rect.width, rect.height);

    if (savedValue) {
      const img = new Image();
      img.onload = () => ctx.drawImage(img, 0, 0, rect.width, rect.height);
      img.src = savedValue;
    }
  }, [isEsign, isFullscreen]);

  const handleClear = useCallback(() => {
    const canvas = canvasRef.current;
    const wrap = wrapRef.current;
    if (!canvas || !wrap) return;
    const ctx = canvas.getContext('2d');
    const rect = wrap.getBoundingClientRect();
    ctx.clearRect(0, 0, rect.width, rect.height);
    setHasStroke(false);
    onChange?.(null);
    onClear?.();
  }, [onChange, onClear]);

  useImperativeHandle(ref, () => ({
    clear: handleClear,
    hasStroke: () => hasStroke,
  }));

  useEffect(() => {
    setupCanvas();
    const wrap = wrapRef.current;
    if (!wrap || typeof ResizeObserver === 'undefined') return undefined;

    const observer = new ResizeObserver(() => setupCanvas());
    observer.observe(wrap);
    return () => observer.disconnect();
  }, [setupCanvas]);

  useEffect(() => {
    if (!drawing.current) {
      setupCanvas();
    }
  }, [value, setupCanvas]);

  useEffect(() => {
    setHasStroke(!!value);
  }, [value]);

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

  const startDraw = (e) => {
    e.preventDefault();
    drawing.current = true;
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    const { x, y } = getPos(e, canvas);
    ctx.beginPath();
    ctx.moveTo(x, y);
  };

  const draw = (e) => {
    if (!drawing.current) return;
    e.preventDefault();
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    const { x, y } = getPos(e, canvas);
    ctx.lineTo(x, y);
    ctx.stroke();
    setHasStroke(true);
  };

  const endDraw = () => {
    if (!drawing.current) return;
    drawing.current = false;
    const canvas = canvasRef.current;
    onChange?.(canvas.toDataURL('image/png'));
  };

  const placeholderText = isEsign ? watermark || '请在此处签名' : isFullscreen ? '请横屏在此处签名' : '请在此处签名';

  return (
    <div
      className={`dt-signature-wrap ${isEsign ? 'dt-signature-wrap--esign' : ''} ${isFullscreen && !isEsign ? 'dt-signature-wrap--fullscreen' : ''}`}
    >
      <div
        ref={wrapRef}
        className={`dt-signature-pad ${hasStroke ? 'dt-signature-pad--signed' : ''} ${isEsign ? 'dt-signature-pad--esign' : ''} ${isFullscreen && !isEsign ? 'dt-signature-pad--fullscreen' : ''}`}
      >
        {!hasStroke && !isEsign && (
          <span className="dt-signature-placeholder" aria-hidden="true">
            {placeholderText}
          </span>
        )}
        {isEsign && !hasStroke && (
          <span className="dt-signature-watermark" aria-hidden="true">
            {watermark || '请在此处签名'}
          </span>
        )}
        <div className={`dt-signature-baseline ${isEsign ? 'dt-signature-baseline--esign' : ''}`} aria-hidden="true" />
        <canvas
          ref={canvasRef}
          className={`dt-signature-canvas ${isEsign ? 'dt-signature-canvas--esign' : ''} ${isFullscreen && !isEsign ? 'dt-signature-canvas--fullscreen' : ''}`}
          onMouseDown={startDraw}
          onMouseMove={draw}
          onMouseUp={endDraw}
          onMouseLeave={endDraw}
          onTouchStart={startDraw}
          onTouchMove={draw}
          onTouchEnd={endDraw}
        />
      </div>
      {!hideActions && (
        <div className={`dt-signature-actions ${isFullscreen ? 'dt-signature-actions--fullscreen' : ''}`}>
          <button type="button" className="dt-btn-secondary dt-signature-clear" onClick={handleClear}>
            清除重签
          </button>
          {hasStroke && (
            <span className="dt-signature-done-badge">
              <span aria-hidden="true">✓</span> 已签名
            </span>
          )}
        </div>
      )}
    </div>
  );
});

export default SignatureCanvas;
