import React, { useState, useEffect } from 'react';

// Redux part
import { useSelector, useDispatch } from 'react-redux';
import { StoreState } from 'store/rootReducer';

// Import actions here

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import app from 'store/app';
import { Form } from 'react-final-form';
import sortBy from 'lodash/sortBy';
import Button from 'components/items/Button';
import Loading from 'components/items/Loading';
import { required, email, composeValidators, isTrue } from 'store/utils/validation';
import { asyncAction, syncAction } from 'store/utils/actions';
import FieldAdapter from 'components/formItems/FieldAdapter';
import styleIdentifiers from './CustomMarketingForm.module.scss';

const styles = classNames.bind(styleIdentifiers);

export interface CustomMarketingFormProps {
  itemComponent: any;
  buttonComponent: any;
}

const MarketingForm = props => {
  const {
    className,
    itemComponent,
    buttonComponent = Button,
    inputProps,
    formData,
    buttonProps,
    lg,
    loadingClassName,
    sendLoader,
    handleSubmit,
    useAdapter,
  } = props;

  function renderList(schema) {
    return schema.list;
  }

  function renderValidation(schema) {
    if (schema.type === 'email' && schema.required) return composeValidators(email, required);
    if (schema.type === 'email' && !schema.required) return composeValidators(email);
    if (schema.type === 'checkbox' && schema.required) return composeValidators(isTrue);
    if (schema.required) return composeValidators(required);
    return null;
  }

  const FieldComponent = itemComponent;
  const ButtonComponent = buttonComponent;

  return (
    <form className={styles('marketing-form', className)} onSubmit={handleSubmit}>
      {FieldComponent &&
        sortBy(formData, 'position').map((item, key) => {
          if (useAdapter) {
            return (
              <FieldAdapter
                name={item.title}
                label={(item.label && item.label[lg]) || item.label}
                key={key}
                placeholder={(item.placeholder && item.placeholder[lg]) || item.placeholder}
                items={renderList(item.schema)}
                component={itemComponent}
                type={item.schema.type !== 'radio' ? item.schema.type : ''}
                validate={renderValidation(item.schema)}
                seed={item.schema && item.schema.type}
                {...item.schema}
                {...inputProps}
              />
            );
          }
          return (
            <FieldComponent
              name={item.title}
              label={(item.label && item.label[lg]) || item.label}
              placeholder={(item.placeholder && item.placeholder[lg]) || item.placeholder}
              {...item.schema}
              type={item.schema.type !== 'radio' ? item.schema.type : ''}
              {...inputProps}
              items={renderList(item.schema)}
              key={key}
              seed={item.schema && item.schema.type}
              validate={renderValidation(item.schema)}
            />
          );
        })}
      {!FieldComponent && <div>Please pass your project Input</div>}
      {ButtonComponent && <ButtonComponent type="submit" {...buttonProps} />}
      {sendLoader && (
        <div className={styles('loading-container', loadingClassName)}>
          <Loading className={styles('loading')} />
        </div>
      )}
    </form>
  );
};

const CustomMarketingForm = (props: CustomMarketingFormProps) => {
  const {
    formId,
    buttonProps,
    onSubmit,
    className,
    inputProps,
    loadingClassName,
    initialValues,
    itemComponent,
    buttonComponent,
    useAdapter,
    noSubmitAPI,
  } = props;
  // mapStateToProps
  const lg = useSelector((state: StoreState) => state.content.lg);
  // Allow to dispatch actions
  const dispatch = useDispatch();

  const getForm = data => dispatch(app.actions.form.get.request.action(data));
  const submitForm = asyncAction(dispatch, app.actions.form.submit);

  const [formData, setFormData] = useState(null);
  const [sendLoader, setSendLoader] = useState(false);

  async function handleSubmit(e) {
    setSendLoader(true);
    if (!e.email && localStorage.getItem('ACemail')) {
      e.email = localStorage.getItem('ACemail');
    }

    let res;
    if (!noSubmitAPI) {
      res = await submitForm({ id: formId, input: { formData: e } });
    }
    if (window && window.vgo && e.email) {
      localStorage.setItem('ACemail', e.email);
      window.vgo('setEmail', e.email);
      window.vgo('process');
    }
    setSendLoader(false);
    if (onSubmit) onSubmit(e, res);
  }

  useEffect(() => {
    if (formId)
      getForm({
        id: formId,
        lg,
        callback: e => {
          if (e?.formData) setFormData(e.formData);
        },
      });
  }, [formId, lg]);

  return (
    <div className={styles('custom-marketing-form')}>
      {formData ? (
        <Form
          component={MarketingForm}
          onSubmit={handleSubmit}
          formData={formData}
          itemComponent={itemComponent}
          buttonComponent={buttonComponent}
          initialValues={initialValues}
          inputProps={inputProps}
          buttonProps={buttonProps}
          loadingClassName={loadingClassName}
          className={className}
          sendLoader={sendLoader}
          lg={lg}
          useAdapter={useAdapter}
        />
      ) : (
        <div className={styles('loading-form')}>Loading ...</div>
      )}
    </div>
  );
};

export default CustomMarketingForm;
