import React, { useState, useRef, ChangeEvent } from 'react'
import { Editor } from '@tiptap/react'
import { X } from 'lucide-react'

interface ImageInsertModalProps {
  editor: Editor | null
  open: boolean
  onClose: () => void
}

const ImageInsertModal: React.FC<ImageInsertModalProps> = ({ editor, open, onClose }) => {
  const [file, setFile] = useState<File | null>(null)
  const [caption, setCaption] = useState('')
  const fileInputRef = useRef<HTMLInputElement>(null)

  if (!open) return null

  const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
    setFile(e.target.files?.[0] ?? null)
  }

  const handleInsert = () => {
    if (!file || !editor) return

    const url = URL.createObjectURL(file)
    editor
        .chain()
        .focus()
        .insertCustomImage({ src: url, caption })
        .run()

    setFile(null)
    setCaption('')
    onClose()
  }

  return (
      <div className="fixed inset-0 bg-black bg-opacity-40 flex items-center justify-center z-50">
        <div className="bg-white rounded-lg p-6 w-96 relative">
          <button
              className="absolute top-2 right-2 text-gray-600 hover:text-gray-900"
              onClick={onClose}
          >
            <X />
          </button>
          <h2 className="text-lg font-medium mb-4">Insert Image</h2>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium mb-1">Image File</label>
              <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  onChange={handleFileChange}
                  className="block w-full text-sm text-gray-700"
              />
            </div>
            <div>
              <label className="block text-sm font-medium mb-1">
                Caption (optional)
              </label>
              <input
                  type="text"
                  value={caption}
                  onChange={(e) => setCaption(e.target.value)}
                  placeholder="Type caption…"
                  className="block w-full border border-gray-300 rounded px-2 py-1 text-sm outline-none focus:ring-2 focus:ring-blue-400"
              />
            </div>
            <button
                disabled={!file}
                onClick={handleInsert}
                className="w-full bg-blue-600 text-white py-2 rounded hover:bg-blue-700 disabled:opacity-50"
            >
              Insert
            </button>
          </div>
        </div>
      </div>
  )
}

export default ImageInsertModal
