import React, { useState } from 'react'
import { NodeViewWrapper, NodeViewContent, NodeViewProps } from '@tiptap/react'
import { ZoomIn, ZoomOut, Trash2 }  from 'lucide-react'

const MIN_SCALE = 0.5
const MAX_SCALE = 2.0
const SCALE_STEP = 0.1

const ImageNodeView: React.FC<NodeViewProps> = ({
                                                  node,
                                                  updateAttributes,
                                                  deleteNode,
                                                  editor,
                                                }) => {
  const [showControls, setShowControls] = useState(false)

  const scale = node.attrs.scale as number

  const handleZoomIn = () => {
    const next = Math.min(MAX_SCALE, scale + SCALE_STEP)
    updateAttributes({ scale: next })
  }

  const handleZoomOut = () => {
    const next = Math.max(MIN_SCALE, scale - SCALE_STEP)
    updateAttributes({ scale: next })
  }

  const handleDelete = () => {
    deleteNode()
  }

  return (
      <NodeViewWrapper
          as="figure"
          className="relative mx-auto"
          onMouseEnter={() => setShowControls(true)}
          onMouseLeave={() => setShowControls(false)}
          style={{ display: 'inline-block' }}
      >
        <img
            src={node.attrs.src}
            alt={node.attrs.alt || ''}
            className="block"
            style={{
              transform: `scale(${scale})`,
              transformOrigin: 'center center',
            }}
        />

        {showControls && (
            <div className="absolute top-1 right-1 flex space-x-1 bg-white bg-opacity-80 rounded shadow">
              <button
                  onClick={handleZoomIn}
                  className="p-1 hover:bg-gray-200 rounded"
                  title="Zoom in"
              >
                <ZoomIn size={16} />
              </button>
              <button
                  onClick={handleZoomOut}
                  className="p-1 hover:bg-gray-200 rounded"
                  title="Zoom out"
              >
                <ZoomOut size={16} />
              </button>
              <button
                  onClick={handleDelete}
                  className="p-1 hover:bg-red-200 rounded"
                  title="Delete"
              >
                <Trash2 size={16} />
              </button>
            </div>
        )}

        <figcaption className="mt-2 text-sm text-gray-500">
          <NodeViewContent
              as="div"
              className="outline-none"
              contentEditable
          />
        </figcaption>
      </NodeViewWrapper>
  )
}

export default ImageNodeView
