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/adminList';
import { Form } from 'react-final-form';
import arrayMutators from 'final-form-arrays';
import config from 'config/general';
import find from 'lodash/find';
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.list.detail);

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

  const submit = values => {
    if (!params.id) {
      add({
        data: {
          ressourceType: params.resource,
          ...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;

  const listInfo = find(config.listEnum, it => it.value === params.resource);

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

export default Manage;
