import React, { useEffect, useState } from "react";
import SignaturePad from "./SignaturePad.jsx";

export default function SignatureModalField({
  value = null,
  label = "Signature",
  disabled = false,
  onChange
}) {
  const [open, setOpen] = useState(false);
  const [previewUrl, setPreviewUrl] = useState(null);

  useEffect(() => {
    if (!value) {
      setPreviewUrl(null);
      return undefined;
    }
    const url = URL.createObjectURL(value);
    setPreviewUrl(url);
    return () => URL.revokeObjectURL(url);
  }, [value]);

  function handleSave(blob) {
    onChange?.(blob || null);
    setOpen(false);
  }

  function handleClear(event) {
    event.stopPropagation();
    onChange?.(null);
  }

  return (
    <>
      <div className="ptw-signature-field">
        <button
          type="button"
          className={`ptw-signature-field__trigger${value ? " ptw-signature-field__trigger--signed" : ""}`}
          disabled={disabled}
          onClick={() => setOpen(true)}
        >
          {previewUrl ? (
            <img className="ptw-signature-field__preview" src={previewUrl} alt="" />
          ) : (
            <span className="ptw-signature-field__placeholder">Click to sign</span>
          )}
        </button>
        {value && !disabled ? (
          <button
            type="button"
            className="ptw-signature-field__clear"
            onClick={handleClear}
          >
            Clear
          </button>
        ) : null}
      </div>

      {open ? (
        <div
          className="swi-modal-backdrop ptw-signature-modal-backdrop"
          role="presentation"
          onClick={() => setOpen(false)}
        >
          <div
            className="swi-modal ptw-signature-modal"
            role="dialog"
            aria-modal="true"
            aria-labelledby="ptw-signature-modal-title"
            onClick={(e) => e.stopPropagation()}
          >
            <header className="swi-modal__header">
              <h2 id="ptw-signature-modal-title" className="swi-modal__title">
                {label}
              </h2>
              <button type="button" className="swi-modal__close" onClick={() => setOpen(false)}>
                Close
              </button>
            </header>
            <div className="swi-modal__body">
              <p className="ptw-signature-modal__hint">
                Draw your signature below, then save.
              </p>
              <SignaturePad
                initialValue={value}
                onChange={handleSave}
                height={280}
                showHint={false}
              />
            </div>
          </div>
        </div>
      ) : null}
    </>
  );
}
