package com.humand.demo.modules.HMTextInput

import android.content.ClipDescription
import android.content.ClipboardManager
import android.content.Context
import android.view.ActionMode
import android.view.Menu
import android.view.MenuItem
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.views.textinput.ReactEditText

class HMTextInputView(context: ThemedReactContext) : ReactEditText(context) {
  interface PasteListener {
    fun onPasteImage()
  }

  var pasteListener: PasteListener? = null
  var pasteImageLabel: String? = null

  private val clipboard by lazy {
    context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
  }

  private val actionModeCallback = object : ActionMode.Callback {
    override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
      // Only show "Paste image" if clipboard has image AND handler is defined
      val hasImage = clipboard.hasPrimaryClip() &&
        (clipboard.primaryClipDescription?.hasMimeType("image/*") == true)
      val hasHandler = pasteListener != null
      
      if (hasImage && hasHandler) {
        menu.clear()
        val label = pasteImageLabel ?: "Paste image"
        menu.add(0, MENU_PASTE_IMAGE_ID, 0, label)
      }
      return true
    }

    override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean = false

    override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
      if (item.itemId == MENU_PASTE_IMAGE_ID && pasteListener != null) {
        pasteListener?.onPasteImage()
        mode.finish()
        return true
      }
      return false
    }

    override fun onDestroyActionMode(mode: ActionMode) {}
  }

  override fun onTextContextMenuItem(id: Int): Boolean {
    // Let RN handle normal paste (it maps to pasteAsPlainText)
    return super.onTextContextMenuItem(id)
  }

  init {
    // Attach custom callback to insertion and selection action modes
    setCustomSelectionActionModeCallback(actionModeCallback)
    setCustomInsertionActionModeCallback(actionModeCallback)
  }

  override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: android.graphics.Rect?) {
    super.onFocusChanged(focused, direction, previouslyFocusedRect)
  }

  companion object {
    private const val MENU_PASTE_IMAGE_ID = 0x7f0f0001
  }
}

