import './style.css'

import { AxiosError } from 'axios'
import { Field, Form, Formik } from 'formik'
import _get from 'lodash/get'
import _identity from 'lodash/identity'
import React, { FC } from 'react'

import { getProfileData, register } from '../../api'
import { CONFIGS } from '../../utils'
import { requiredValidator } from '../../validators'
import { CustomField } from '../common/CustomField'
import { PoweredBy } from '../common/PoweredBy'

interface Props {
  onClose: () => void;
  onRegister: () => void;
  onGetProfileDataSuccess: (res: any) => void;
  onGetProfileDataError: (e: AxiosError) => void;
  showPoweredByImage?: boolean;
}

export const RegisterModal: FC<Props> = ({
  onClose,
  onGetProfileDataSuccess = _identity,
  onGetProfileDataError = _identity,
  showPoweredByImage = false,
}) => (
  <div
    style={{
      display: 'flex',
      position: 'absolute',
      top: 0,
      bottom: 0,
      right: 0,
      left: 0,
      backgroundColor: 'white',
      alignItems: 'center',
      justifyContent: 'center',
      zIndex: 10,
    }}
  >
    <Formik
      initialValues={{
        firstName: '',
        lastName: '',
        email: '',
        password: '',
        confirmPassword: '',
      }}
      onSubmit={async ({ firstName, lastName, email, password, confirmPassword }) => {
        const bodyFormData = new FormData()
        bodyFormData.append('first_name', firstName)
        bodyFormData.append('last_name', lastName)
        bodyFormData.append('email', email)
        bodyFormData.append('password', password)
        bodyFormData.append('password_confirmation', confirmPassword)
        bodyFormData.append('client_id', CONFIGS.CLIENT_ID)
        bodyFormData.append('client_secret', CONFIGS.CLIENT_SECRET)
        await register(bodyFormData)
        let profileResponse = null

        try {
          profileResponse = await getProfileData()
          onGetProfileDataSuccess(profileResponse.data)
        } catch (e) {
          onGetProfileDataError(e as AxiosError)
          return
        }

        const profileSpecifiedData = _get(profileResponse, 'data')
        const profileDataObj = {
          id: profileSpecifiedData.id,
          first_name: profileSpecifiedData.firstName,
          last_name: profileSpecifiedData.lastName,
          email: profileSpecifiedData.email,
        }
        if (typeof window !== 'undefined') {
          window.localStorage.setItem('user_data', JSON.stringify(profileDataObj))
        }
        onClose()
      }}
    >
      {props => (
        <Form onSubmit={props.handleSubmit}>
          <div className="register-container">
            <div>Create account</div>
            <button type="button" onClick={onClose}>
              Close
            </button>
            <div className="register-container__twoFields">
              <div className="is-half">
                <Field
                  name="firstName"
                  label="First Name"
                  type="text"
                  component={CustomField}
                  theme="light"
                  validate={requiredValidator()}
                />
              </div>
              <div className="is-half">
                <Field
                  name="lastName"
                  label="Last Name"
                  type="text"
                  component={CustomField}
                  theme="light"
                  validate={requiredValidator()}
                />
              </div>
            </div>
            <div className="register-container__singleField">
              <div className="">
                <Field
                  name="email"
                  label="Email"
                  type="email"
                  component={CustomField}
                  theme="light"
                  validate={requiredValidator()}
                />
              </div>
            </div>
            <div className="register-container__twoFields">
              <div className="is-half">
                <Field
                  name="password"
                  label="Password"
                  type="password"
                  component={CustomField}
                  theme="light"
                  validate={requiredValidator()}
                />
              </div>
              <div className="is-half">
                <Field
                  name="confirmPassword"
                  label="Confirm Password"
                  type="password"
                  component={CustomField}
                  theme="light"
                  validate={requiredValidator()}
                />
              </div>
            </div>
          </div>
          <button type="submit">Submit</button>
          {showPoweredByImage ? <PoweredBy /> : null}
        </Form>
      )}
    </Formik>
  </div>
)
