import { Field, Form, Formik, FormikProps } from 'formik'
import _identity from 'lodash/identity'
import React from 'react'

import { fieldDataAdapter } from '../../adapters/customFields'
import {
  getFieldComponent,
  getFieldLabel,
  getValidateFunctions,
} from '../billing-info-container/utils'
import { CustomFieldTypes } from './index'

interface HolderCustomFieldsProps {
  initialValues: { [key: string]: any };
  fields: Array<CustomFieldTypes>;
  handleFormSubmit?: (values: Record<string, any>) => void;
  handleFormClose?: () => void;
}

const CustomFieldsForm = ({
  initialValues = {},
  fields = [],
  handleFormSubmit = _identity,
  handleFormClose = _identity,
}: HolderCustomFieldsProps) => (
  <Formik
    initialValues={initialValues}
    onSubmit={values => handleFormSubmit(values)}
    enableReinitialize={true}
  >
    {(props: FormikProps<any>) => (
      <Form>
        <div className="updatable-custom-fields">
          {fields.map((customField: CustomFieldTypes) => {
            const adaptedCustomField = fieldDataAdapter(customField)
            return (
              <Field
                key={customField.id}
                name={customField.name}
                label={getFieldLabel(customField)}
                component={getFieldComponent(adaptedCustomField)}
                validate={getValidateFunctions(
                  customField,
                  [],
                  props.values,
                  props.errors
                )}
                isMultiple={adaptedCustomField.isMultiple}
                radios={adaptedCustomField.radios}
                options={adaptedCustomField.options}
              />
            )
          })}
        </div>
        <div className="buttons-block">
          <button
            className="cancel-btn"
            type="button"
            onClick={() => {
              props.resetForm()
              handleFormClose()
            }}
          >
            Cancel
          </button>
          <button className="submit-btn" type="submit">
            Update ticket
          </button>
        </div>
      </Form>
    )}
  </Formik>
)

export { CustomFieldsForm }
