import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import { Eraser } from 'lucide-react';
import * as React from 'react';
import SignaturePad from 'react-signature-canvas';

interface SignaturePadFieldProps {
    label: string;
    description?: string;
    value?: string | null;
    existingImageUrl?: string | null;
    onChange: (base64: string | null) => void;
    className?: string;
}

/**
 * Lightweight wrapper around react-signature-canvas that:
 * - Resizes the canvas to its container with DPR awareness
 * - Returns base64 data URLs (PNG)
 * - Supports displaying an existing image (when re-editing)
 */
export function SignaturePadField({
    label,
    description,
    value,
    existingImageUrl,
    onChange,
    className,
}: SignaturePadFieldProps) {
    const padRef = React.useRef<SignaturePad>(null);
    const wrapperRef = React.useRef<HTMLDivElement>(null);
    const [isDrawn, setIsDrawn] = React.useState<boolean>(Boolean(value));

    // Resize the canvas to match its CSS size (avoids stretched lines)
    React.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;
            const ctx = canvas.getContext('2d');
            ctx?.scale(ratio, ratio);
            padRef.current?.clear();
            if (value) {
                padRef.current?.fromDataURL(value);
                setIsDrawn(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()) {
            setIsDrawn(false);
            onChange(null);
            return;
        }
        const dataUrl = pad.toDataURL('image/png');
        setIsDrawn(true);
        onChange(dataUrl);
    };

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

    return (
        <div className={cn('flex flex-col gap-2', className)}>
            <div className="flex items-center justify-between gap-2">
                <div>
                    <p className="text-sm font-medium">{label}</p>
                    {description && <p className="text-xs text-muted-foreground">{description}</p>}
                </div>
                <Button type="button" variant="ghost" size="sm" onClick={clear} disabled={!isDrawn}>
                    <Eraser className="mr-1 h-4 w-4" />
                    Effacer
                </Button>
            </div>
            <div
                ref={wrapperRef}
                className="relative h-40 w-full rounded-md border bg-white"
                style={{ touchAction: 'none' }}
            >
                {!isDrawn && existingImageUrl && (
                    <img
                        src={existingImageUrl}
                        alt="Signature actuelle"
                        className="pointer-events-none absolute inset-0 m-auto max-h-full max-w-full object-contain opacity-40"
                    />
                )}
                <SignaturePad
                    ref={padRef}
                    onEnd={handleEnd}
                    canvasProps={{ className: 'block h-full w-full' }}
                />
            </div>
        </div>
    );
}
