import { ConfirmHotKeys } from '@any-ui/core'
import { browserHistory } from '@any-ui/core/navigation'
import type { AnyObject, FormState } from 'final-form'
import React, { createContext, FC, useContext } from 'react'
import { useFormState } from 'react-final-form'
import type { IFormActionProps } from '..'

interface IFormContext extends IFormActionProps, Partial<FormState<AnyObject>> {
  canSubmit: boolean
  submitDisabled: boolean
  submitting: boolean
  triggerCancel: () => void
  triggerSubmit: () => void
}
const throwNoContextError = () => {
  throw new Error('There is no context provided')
}

const FormContext = createContext<IFormContext>({
  canSubmit: false,
  dirtySinceLastSubmit: false,
  // change: throwNoContextError,
  error: null,
  submitDisabled: true,
  submitting: false,
  triggerCancel: throwNoContextError,
  triggerSubmit: throwNoContextError,
  validating: false,
})

// export { useForm as useFormContext } from 'react-final-form'

export const useFormContext = () => useContext(FormContext)

export const FormContextProvider: FC<FormState<AnyObject> &
  IFormActionProps> = ({
  cancelLabel,
  onCancel,
hideCancel,

  // change,
  children,
  error,
  isNew,
  pristine,
  // @ts-ignore
  handleSubmit,
  submitLabel,
  valid,
}) => {
  const { validating, dirtySinceLastSubmit, submitting } = useFormState()
  const disabled =
    (!dirtySinceLastSubmit && !valid) || (!isNew && pristine) || submitting

  const triggerCancel = () => {
    console.log(onCancel)
    if (onCancel) {
      onCancel()
  } else {
      alert('xxx')
      browserHistory.push('/')
    }}
  const triggerSubmit = () => {
    if (!disabled) {
      return handleSubmit()
    } else {
      return null
    }
  }

  const context: IFormContext = {
    canSubmit: !disabled,
    cancelLabel,
    dirtySinceLastSubmit,
    // change,
    error,
    isNew,
    submitDisabled: disabled,
    submitLabel,
    submitting,
    triggerCancel,
    triggerSubmit,
    validating,
    hideCancel
  }
  return (
    <FormContext.Provider value={context}>
      <ConfirmHotKeys onConfirm={triggerSubmit} onCancel={triggerCancel}>
        {children}
      </ConfirmHotKeys>
    </FormContext.Provider>
  )
}
