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 GenericForm from 'components/forms/GenericForm';
import list from 'store/list';
import options from 'config/adminErrors';
import error from 'store/error';
import { Form } from 'react-final-form';
import arrayMutators from 'final-form-arrays';
import styleIdentifiers from './manage.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type ManageProps = StateProps & DispatchProps & OwnProps;

const Manage = (props: ManageProps) => {
  const {
    history,
    match: { params },
  } = props;

  // mapStateToProps
  const lg = useSelector((state: StoreState) => state.content.lg);
  const detail = useSelector((state: StoreState) => state.error.detail);

  // Allow to dispatch actions
  const dispatch = useDispatch();
  const load = data => dispatch(error.actions.detail.request.action(data));
  const update = data => dispatch(error.actions.update.request.action(data));
  const add = data => dispatch(error.actions.add.request.action(data));

  const submit = values => {
    if (!params.id) {
      add({
        data: {
          ...values,
        },
        callback: () => {
          history.goBack();
        },
      });
    } else {
      update({
        id: params.id,
        data: values,
        callback: () => {
          history.goBack();
        },
      });
    }
  };

  useEffect(() => {
    if (!params.id) return;
    load({
      id: params.id,
    });
  }, [params.id]);

  const data = detail && detail.data;
  return (
    <div className={styles('manage')}>
      {(!params.id || data) && (
        <Form
          component={GenericForm}
          mutators={{ ...arrayMutators }}
          withHeader
          initialValues={params.id ? data : {}}
          fields={options.model}
          onSubmit={submit}
          title={options?.title || (detail?.data?.title && detail.data.title[lg])}
        />
      )}
    </div>
  );
};

export default Manage;
