import React, { useEffect, useRef, useState } from 'react'
import cx from 'classnames'
import {
  complement,
  defaultTo,
  find,
  isNil,
  propEq,
  type as ramdaType,
} from 'ramda'
import MTEntityList from './mt-entity-list'
import MTIcon from './mt-icon'

const isDefined = complement(isNil)
const findWithKey = (key, entities) => find(propEq('key', key), entities)

const getFormComponent = (type, withFormRenderer, forms, Component) => {
  switch (type) {
    case 'form': return withFormRenderer(forms)
    case 'component': return Component
    default: return () => null
  }
}

function MTOmniCreate (props) {
  const {
    entities,
    onSubmit,
    onChange,
    children,
    initialEntityKey = '',
    chosenTabIndex = 0,
    className,
    ...otherProps
  } = props
  const [ chosenEntityKey, setChosenEntityKey ] = useState(initialEntityKey)
  const [ showForm, setShowForm ] = useState(isDefined(initialEntityKey))

  const ref = useRef()
  useEffect(() => {
    ref.current.focus()
  }, [])

  const chosenEntity = findWithKey(chosenEntityKey, entities)

  const {
    withFormRenderer, forms, type, Component,
  } = defaultTo({}, chosenEntity)

  const handleChooseEntity = (key) => {
    setChosenEntityKey(key)
    setShowForm(true)
  }

  const FormComponent = getFormComponent(type, withFormRenderer, forms, Component)

  const tabIndex = ramdaType(chosenTabIndex) !== 'Number' ? 0 : chosenTabIndex

  return (
    <div { ...otherProps } className={ cx('omnicreate', className) } ref={ ref } tabIndex={ -1 }>
      <div className="omnicreate-header">
        <MTIcon type="add" className="omnicreate-header__icon" />
        <div className="omnicreate-header__title">
          <span className="omnicreate-header__title--strong">Quick Create</span>
        </div>
      </div>
      <div className="omnicreate-main">
        <div className="omnicreate-main__list">
          <MTEntityList
            entities={ entities }
            initialEntityKey={ chosenEntityKey }
            onEntityClick={ handleChooseEntity }
          />
        </div>
        { showForm
          ? (
            <div className="omnicreate-main__form">
              <FormComponent
                onSubmit={ (formId, data) => onSubmit(chosenEntity.name, formId, data) }
                onFormChange={
                  (formId, key, value) => onChange(chosenEntity.name, formId, key, value)
                }
                initialTabIndex={ tabIndex }
              />
            </div>
          )
          : null
        }
      </div>
      <div className="omnicreate__children">
        { children }
      </div>
    </div>
  )
}

export default MTOmniCreate
