import { useRef, useEffect, useState, useCallback } from 'react'
import * as Y from 'yjs'
import { IndexeddbPersistence } from 'y-indexeddb'

/**
 * Manages a Y.Doc for a given document ID.
 * Persists to IndexedDB for offline support.
 */
export function useYDoc(documentId: string | null) {
  const ydocRef = useRef<Y.Doc | null>(null)
  const persistenceRef = useRef<IndexeddbPersistence | null>(null)
  const [ytext, setYtext] = useState<Y.Text | null>(null)
  const [ready, setReady] = useState(false)

  useEffect(() => {
    if (!documentId) {
      setYtext(null)
      setReady(false)
      return
    }

    const ydoc = new Y.Doc()
    ydocRef.current = ydoc

    const text = ydoc.getText('content')
    setYtext(text)

    // Persist to IndexedDB
    const persistence = new IndexeddbPersistence(`calctext-${documentId}`, ydoc)
    persistenceRef.current = persistence

    persistence.on('synced', () => {
      setReady(true)
    })

    return () => {
      persistence.destroy()
      ydoc.destroy()
      ydocRef.current = null
      persistenceRef.current = null
      setYtext(null)
      setReady(false)
    }
  }, [documentId])

  /** Get the current document content as a plain string */
  const getContent = useCallback((): string => {
    return ytext?.toString() ?? ''
  }, [ytext])

  /** Initialize the Y.Doc with content if it's empty (first time) */
  const initContent = useCallback((content: string) => {
    if (!ytext || !ydocRef.current) return
    if (ytext.length === 0 && content.length > 0) {
      ydocRef.current.transact(() => {
        ytext.insert(0, content)
      })
    }
  }, [ytext])

  return {
    ydoc: ydocRef.current,
    ytext,
    ready,
    getContent,
    initContent,
  }
}
