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

import { useFormValidation } from '../../lib/forms'
import { USER_SIGNUP, CURRENT_USER } from './graphql'
import { signupValidation } from './validation'

const initialValues = {
  name: 'Tomi',
  email: 'tomi@cvetic.ch',
  password: '1234',
  passwordAgain: '1234'
}

async function onSubmit(values, mutation) {
  try {
    const user = await mutation({ variables: values })
    console.log(user)
  } catch (error) {
    console.log(error)
  }
}

const SignupAdoption = adopt({
  mutation: ({ render }) => (
    <Mutation
      mutation={USER_SIGNUP}
      refetchQueries={[{ query: CURRENT_USER }]}
    >{(signup, { data, error, loading }) => render({ signup, data, error, loading, render })}
    </Mutation>
  ),
  form: ({ mutation, render }) => (
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      onSubmit={values => onSubmit(values, mutation)}
    >
      {render}
    </Formik>
  )
})

const SignupForm = props => (
  <SignupAdoption>
    {({ form, mutation: { signup, data, error, loading } }) => (
      <Form>
        <TextInput
          label='Name'
          name='name'
          type='text'
          placeholder='Name'
        />
        <TextInput
          label='Email'
          name='email'
          type='email'
          placeholder='Email Address'
        />
        <TextInput
          label='Password'
          name='password'
          type='password'
          placeholder='1234'
        />
        <TextInput
          label='Repeat password'
          name='passwordAgain'
          type='password'
          placeholder='1234'
        />
        <button type='reset' disabled={loading}>Sign Up!</button>
        <button type='submit' disabled={loading}>Sign Up!</button>

        <style jsx>
          {`
            select, input {
              color: rgba(0,0,127,1);
            }

            .error {
              font-size: 12px;
              color: rgba(127,0,0,1);
              width: 400px;
              margin-top: 0.25rem;
            }

            .error:before {
              content: "❌ ";
              font-size: 10px;
            }

            label {
              color: red;
              margin-top: 1rem;
            }
          `}
        </style>
      </Form>
    )}
  </SignupAdoption>
)

export default SignupForm
