import { Query, Mutation } from 'react-apollo'
import { adopt } from 'react-adopt'
import { Formik, Form } from 'formik'

import { TextInput } from '../lib/forms'
import { BLOCKS, CREATE_BLOCK } from '../lib/graphql'
import Overlay from './overlay'

const ContentInput = props => {
  const [displayForm, setDisplayForm] = React.useState(false)

  const toggleForm = ev => {
    ev.preventDefault()
    setDisplayForm(!displayForm)
  }

  return (
    <Query query={BLOCKS}>
      {({ data, error, loading }) => (
        <>
          <label>Training type</label>
          <div>
            <select disabled={(loading || error)}>
              {data ? data.trainingTypes.map(trainingType =>
                <option key={trainingType.id} value={trainingType.id}>{trainingType.name}</option>
              ) : null}
            </select>
            <button
              type='button'
              onClick={toggleForm}
            >Add
            </button>
          </div>
          {displayForm ? (
            <Overlay close={toggleForm}>
              <ContentForm />
            </Overlay>
          ) : null}

          <style jsx>
            {`
              div {
                width: 100%;
              }
            `}
          </style>
        </>
      )}
    </Query>
  )
}

const ContentAdoption = adopt({
  mutation: ({ render }) => (
    <Mutation
      mutation={CREATE_BLOCK}
      refetchQueries={[{ query: BLOCKS }]}
    >
      {(createTrainingType, { data, error, loading }) => render({ createTrainingType, data, error, loading })}
    </Mutation>
  ),
  form: ({ mutation: { createTrainingType }, render }) => (
    <Formik
      initialValues={{
        name: '',
        description: ''
      }}
      onSubmit={values => createTrainingType({ variables: values })}
    >
      {render}
    </Formik>
  )
})

const ContentForm = props => (
  <ContentAdoption>{({ mutation, form }) => (
    <Form>
      <TextInput
        label='Name'
        name='name'
        type='text'
      />
      <TextInput
        label='Description'
        name='description'
        type='text'
      />
      <button type='reset'>Reset</button>
      <button type='submit'>Save</button>
    </Form>
  )}
  </ContentAdoption>
)

export { ContentForm }
export default ContentInput
