import { FC, useCallback } from 'react'
import ReactFocusLock from 'react-focus-lock'

import { ChildrenProp } from '../core'
import { FocusLockProps } from './focusLock.types'

/**
 * Traps the focus within the provided content.
 *
 * Tabbing using the keyboard will only cycle through the children and won't leave the boundary of the FocusLock wrapper.
 */

export const FocusLock: FC<FocusLockProps & ChildrenProp> = props => {
  const {
    autoFocus,
    children,
    crossFrame,
    finalFocusRef,
    initialFocusRef,
    isDisabled,
    persistentFocus,
    returnFocus: returnFocusProp,
  } = props

  const onActivation = useCallback(() => {
    initialFocusRef?.current?.focus()
  }, [initialFocusRef])

  const onDeactivation = useCallback(() => {
    finalFocusRef?.current?.focus()
  }, [finalFocusRef])

  const returnFocus = returnFocusProp && !finalFocusRef

  return (
    <ReactFocusLock
      autoFocus={autoFocus}
      crossFrame={crossFrame}
      disabled={isDisabled}
      onActivation={onActivation}
      onDeactivation={onDeactivation}
      persistentFocus={persistentFocus}
      returnFocus={returnFocus}
    >
      {children}
    </ReactFocusLock>
  )
}

FocusLock.displayName = 'FocusLock'
export default FocusLock
