import { Formik, Form } from 'formik'
import { Mutation } from 'react-apollo'
import { adopt } from 'react-adopt'
import { useMutation } from '@apollo/react-hooks'
import * as Yup from 'yup'

import { TextInput } from '../../lib/forms'
import TrainingTypeInput from './trainingType'
import { CREATE_TRAINING } from '../../lib/graphql'

const TrainingAdoption = adopt({
  mutation: ({ render }) => (
    <Mutation mutation={CREATE_TRAINING}>
      {(createTraining, { loading, data, error }) => render({ createTraining, loading, data, error })}
    </Mutation>
  ),
  formik: ({ mutation: { createTraining }, render }) => (
    <Formik
      initialValues={{
        title: 'Winter HIIT 7',
        type: 'HIIT',
        content: [],
        trainingDate: Date.now(),
        location: 'Yoga room',
        attendance: 0,
        published: false
      }}
      validationSchema={Yup.object({
        title: Yup.string()
          .required('required'),
        type: Yup.string(),
        trainingDate: Yup.date()
          .required('required'),
        location: Yup.string()
          .required('required'),
        attendance: Yup.number()
          .integer('integer number'),
        published: Yup.bool()
      })}
      onSubmit={values => console.log(values)}
    >
      {render}
    </Formik>
  )
})

const TrainingForm = props => (
  <TrainingAdoption>
    {({ mutation: { createTraining, data, loading, error }, formik }) => (
      <section>
        <Form>
          <h2>Create Training</h2>
          <TextInput
            label='Title'
            name='title'
            type='text'
            placeholder='title'
          />
          <TrainingTypeInput
            label='Type'
            name='type'
          />
          <ContentInput
            label='Content'
            name='content'
          />
          <TextInput
            label='Training date'
            name='trainingDate'
            type='date'
          />
          <TextInput
            label='Location'
            name='location'
            type='text'
            placeholder='location'
          />
          <TextInput
            label='Attendance'
            name='attendance'
            type='number'
            placeholder='attendance'
          />
          <TextInput
            label='Published'
            name='published'
            type='text'
            placeholder='published'
          />
          <button type='submit'>Create!</button>
        </Form>

        <style jsx>{`
        section > :global(form) {
          display: grid;
          grid-template-columns: 1fr 2fr;
        }

        section :global(label) {
          grid-column: 1/2;
        }

        section :global(input),
        section :global(text) {
          grid-column: 2/3;
        }

        section :global(h2) {
          grid-column: 1/3;
        }
      `}</style>
      </section>
    )}
  </TrainingAdoption>
)

export default TrainingForm
