'use client'

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

interface NotebookDragContextValue {
  draggedNoteId: string | null
  dragOverNotebookId: string | null
  startDrag: (noteId: string) => void
  endDrag: () => void
  dragOver: (notebookId: string | null) => void
  isDragging: boolean
  isDragOver: boolean
}

const NotebookDragContext = createContext<NotebookDragContextValue | null>(null)

export function useNotebookDrag() {
  const context = useContext(NotebookDragContext)
  if (!context) {
    throw new Error('useNotebookDrag must be used within NotebookDragProvider')
  }
  return context
}

interface NotebookDragProviderProps {
  children: ReactNode
}

export function NotebookDragProvider({ children }: NotebookDragProviderProps) {
  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(() => ({
    draggedNoteId,
    dragOverNotebookId,
    startDrag,
    endDrag,
    dragOver,
    isDragging,
    isDragOver,
  }), [draggedNoteId, dragOverNotebookId, startDrag, endDrag, dragOver, isDragging, isDragOver])

  return (
    <NotebookDragContext.Provider value={value}>
      {children}
    </NotebookDragContext.Provider>
  )
}
