'use client';

import { useRef, useState } from 'react';
import SignatureCanvas from 'react-signature-canvas';
import { FiRefreshCw, FiCheck } from 'react-icons/fi';

interface SignaturePadProps {
  onSave: (signatureData: string) => void;
  onCancel?: () => void;
}

export default function SignaturePad({ onSave, onCancel }: SignaturePadProps) {
  const sigCanvas = useRef<SignatureCanvas>(null);
  const [isEmpty, setIsEmpty] = useState(true);

  const clear = () => {
    sigCanvas.current?.clear();
    setIsEmpty(true);
  };

  const save = () => {
    if (sigCanvas.current && !sigCanvas.current.isEmpty()) {
      const dataUrl = sigCanvas.current.toDataURL('image/png');
      onSave(dataUrl);
    }
  };

  const handleEnd = () => {
    setIsEmpty(sigCanvas.current?.isEmpty() || false);
  };

  return (
    <div className="space-y-4">
      <div className="border-2 border-gray-300 rounded-lg overflow-hidden bg-white">
        <SignatureCanvas
          ref={sigCanvas}
          canvasProps={{
            className: 'w-full h-64 cursor-crosshair',
          }}
          onEnd={handleEnd}
        />
      </div>

      <div className="flex gap-3">
        <button
          type="button"
          onClick={clear}
          className="flex items-center gap-2 px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 transition-colors"
        >
          <FiRefreshCw /> Zurücksetzen
        </button>
        
        {onCancel && (
          <button
            type="button"
            onClick={onCancel}
            className="flex items-center gap-2 px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 transition-colors"
          >
            Abbrechen
          </button>
        )}

        <button
          type="button"
          onClick={save}
          disabled={isEmpty}
          className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:bg-gray-400 disabled:cursor-not-allowed"
        >
          <FiCheck /> Unterschrift speichern
        </button>
      </div>

      <p className="text-sm text-gray-600">
        Bitte unterschreiben Sie mit Maus, Trackpad oder Touchscreen im Feld oben.
      </p>
    </div>
  );
}
