import { useEffect, useRef, useState } from 'react';
import SignaturePad from 'react-signature-canvas';

const MINT = '#31b08f';
const DARK_TEAL = '#1b4e4d';

interface InlineSignatureWidgetProps {
    /** "sender" | "recipient" — label & color hint */
    slot: 'sender' | 'recipient';
    /** Controlled base64 PNG (data URL) — null when not yet drawn. */
    value: string | null;
    onChange: (base64: string | null) => void;
}

/**
 * Inline signature widget rendered inside a document signature slot.
 * Visual style mirrors the existing mandat (PropertyContract) signature
 * box — rounded MINT border, full-width canvas, Effacer button.
 */
export function InlineSignatureWidget({ slot, value, onChange }: InlineSignatureWidgetProps) {
    const padRef = useRef<SignaturePad>(null);
    const wrapperRef = useRef<HTMLDivElement>(null);
    const [hasInk, setHasInk] = useState<boolean>(Boolean(value));

    // Match the SignaturePadField resize-on-mount pattern so the canvas
    // pixel size tracks its CSS size (sharp lines at any DPI).
    useEffect(() => {
        const resize = () => {
            const canvas = padRef.current?.getCanvas();
            const wrapper = wrapperRef.current;
            if (!canvas || !wrapper) return;
            const ratio = Math.max(window.devicePixelRatio || 1, 1);
            canvas.width = wrapper.clientWidth * ratio;
            canvas.height = wrapper.clientHeight * ratio;
            canvas.getContext('2d')?.scale(ratio, ratio);
            padRef.current?.clear();
            if (value) {
                padRef.current?.fromDataURL(value);
                setHasInk(true);
            }
        };
        resize();
        window.addEventListener('resize', resize);
        return () => window.removeEventListener('resize', resize);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const handleEnd = () => {
        const pad = padRef.current;
        if (!pad) return;
        if (pad.isEmpty()) {
            setHasInk(false);
            onChange(null);
            return;
        }
        setHasInk(true);
        onChange(pad.toDataURL('image/png'));
    };

    const clear = () => {
        padRef.current?.clear();
        setHasInk(false);
        onChange(null);
    };

    return (
        <div
            className="not-prose mx-auto w-full max-w-xs text-center"
            style={{ color: DARK_TEAL }}
            contentEditable={false}
        >
            <p className="mb-2 text-base font-semibold text-black">
                {slot === 'sender' ? 'Signature Conciergerie' : 'Signature du Partenaire'}
            </p>
            <div
                ref={wrapperRef}
                className="relative mx-auto h-48 w-full overflow-hidden rounded border border-gray-400 bg-white"
                style={{ touchAction: 'none' }}
            >
                <SignaturePad
                    ref={padRef}
                    onEnd={handleEnd}
                    canvasProps={{ className: 'block h-full w-full' }}
                />
            </div>
            <div className="mt-2 flex items-center justify-between">
                <span className="text-xs italic" style={{ color: hasInk ? MINT : '#94a3b8' }}>
                    {hasInk ? 'Signature capturée' : 'Dessinez ici avec la souris ou le doigt'}
                </span>
                <button
                    type="button"
                    onClick={clear}
                    disabled={!hasInk}
                    className="rounded px-3 py-1 text-xs text-white transition disabled:opacity-40"
                    style={{ backgroundColor: hasInk ? DARK_TEAL : '#94a3b8' }}
                >
                    Effacer
                </button>
            </div>
        </div>
    );
}
