import FormProvider from 'domains/forms/provider'
import { visibilityStates } from 'domains/visibility/constants'
import { useVisibility } from 'domains/visibility/hooks'
import { useCallback } from 'preact/hooks'
import {
  useSeamlyCommands,
  useSkiplinkTarget,
  useSkiplinkTargetFocusing,
} from 'ui/hooks/seamly-hooks'
import TextEntryForm from './text-entry-form'

export const textEntryControlName = 'textMessageEntry'

export default function TextEntry({ ...props }) {
  const { isOpen, setVisibility } = useVisibility()
  const skipLinkId = useSkiplinkTarget()
  const focusSkipLinkTarget = useSkiplinkTargetFocusing()
  const { sendMessage } = useSeamlyCommands()
  const handleSubmit = useCallback(
    (values, { updateControlValue }) => {
      sendMessage({ body: values[textEntryControlName] })
      updateControlValue(textEntryControlName, '')
      focusSkipLinkTarget()

      if (!isOpen) {
        setVisibility({ visibility: visibilityStates.open })
      }
    },
    [sendMessage, focusSkipLinkTarget, isOpen, setVisibility],
  )

  return (
    <FormProvider
      {...props}
      formId="textEntry"
      persistData={true}
      onSubmit={handleSubmit}
    >
      <TextEntryForm
        controlName={textEntryControlName}
        skipLinkId={skipLinkId}
      />
    </FormProvider>
  )
}
