'use client'

import { createContext, useContext, useState, useCallback, useMemo, type ReactNode } from 'react'

export type HomeUiControls = {
  openNoteComposer: () => void
}

interface EditorUIContextValue {
  // HomeView controls
  controls: HomeUiControls | null
  setControls: (c: HomeUiControls | null) => void

  // NotebookDrag controls
  draggedNoteId: string | null
  dragOverNotebookId: string | null
  startDrag: (noteId: string) => void
  endDrag: () => void
  dragOver: (notebookId: string | null) => void
  isDragging: boolean
  isDragOver: boolean
}

const EditorUIContext = createContext<EditorUIContextValue | null>(null)

export function EditorUIProvider({ children }: { children: ReactNode }) {
  // HomeView state
  const [controls, setControls] = useState<HomeUiControls | null>(null)

  // NotebookDrag state
  const [draggedNoteId, setDraggedNoteId] = useState<string | null>(null)
  const [dragOverNotebookId, setDragOverNotebookId] = useState<string | null>(null)

  const startDrag = useCallback((noteId: string) => {
    setDraggedNoteId(noteId)
  }, [])

  const endDrag = useCallback(() => {
    setDraggedNoteId(null)
    setDragOverNotebookId(null)
  }, [])

  const dragOver = useCallback((notebookId: string | null) => {
    setDragOverNotebookId(notebookId)
  }, [])

  const isDragging = draggedNoteId !== null
  const isDragOver = dragOverNotebookId !== null

  const value = useMemo<EditorUIContextValue>(() => ({
    controls,
    setControls,
    draggedNoteId,
    dragOverNotebookId,
    startDrag,
    endDrag,
    dragOver,
    isDragging,
    isDragOver,
  }), [controls, draggedNoteId, dragOverNotebookId, startDrag, endDrag, dragOver, isDragging, isDragOver])

  return <EditorUIContext.Provider value={value}>{children}</EditorUIContext.Provider>
}

export function useEditorUI() {
  const ctx = useContext(EditorUIContext)
  if (!ctx) throw new Error('useEditorUI must be used within EditorUIProvider')
  return ctx
}

export function useEditorUIOptional(): EditorUIContextValue | null {
  return useContext(EditorUIContext)
}