import type { Ref } from 'vue'
import { ref, nextTick } from 'vue'

type NodeType<T> = T & { id: string; label: string; children?: T[] }
type LocateResult<T> = { node: NodeType<T>; parent: NodeType<T> | null; container: NodeType<T>[]; index: number } | null

export const useInlineEdit = <T>(params: {
  dataRef: Ref<NodeType<T>[]>;
  locate: (id: string) => LocateResult<T>;
}) => {
  const { dataRef, locate } = params
  const editingId = ref<string | null>(null)
  const editingLabel = ref('')
  const editingOriginalLabel = ref('')

  const startEdit = (nodeData: NodeType<T>) => {
    editingId.value = nodeData.id
    editingLabel.value = nodeData.label
    editingOriginalLabel.value = nodeData.label
    nextTick(() => {
      const el = document.getElementById(`edit-${nodeData.id}`) as HTMLInputElement | null
      el?.focus()
      el?.select()
    })
  }

  const saveEdit = () => {
    if (!editingId.value) return
    const target = locate(editingId.value)
    if (!target) { editingId.value = null; return }
    const next = editingLabel.value.trim()
    if (next) target.node.label = next
    dataRef.value = [...dataRef.value]
    editingId.value = null
  }

  const cancelEdit = () => {
    if (!editingId.value) return
    editingLabel.value = editingOriginalLabel.value
    editingId.value = null
  }

  return { editingId, editingLabel, editingOriginalLabel, startEdit, saveEdit, cancelEdit }
}

