'use client'

import { useState, useEffect, useCallback } from 'react'

interface ContentLock {
  lockedBy: string | null
  lockedAt: Date | null
  isLocked: boolean
  isLockedByMe: boolean
}

export function useContentLock(
  documentId: string | undefined,
  userId: string,
): ContentLock & {
  acquireLock: () => Promise<boolean>
  releaseLock: () => Promise<void>
} {
  const [lock, setLock] = useState<ContentLock>({
    lockedBy: null,
    lockedAt: null,
    isLocked: false,
    isLockedByMe: false,
  })

  const acquireLock = useCallback(async () => {
    if (!documentId) return false
    setLock({
      lockedBy: userId,
      lockedAt: new Date(),
      isLocked: true,
      isLockedByMe: true,
    })
    return true
  }, [documentId, userId])

  const releaseLock = useCallback(async () => {
    setLock({
      lockedBy: null,
      lockedAt: null,
      isLocked: false,
      isLockedByMe: false,
    })
  }, [])

  useEffect(() => {
    return () => {
      if (lock.isLockedByMe) {
        releaseLock()
      }
    }
  }, [lock.isLockedByMe, releaseLock])

  return { ...lock, acquireLock, releaseLock }
}
