import React, { useState, useEffect } from 'react';
import classNames from 'classnames/bind';
import GenericForm from 'components/forms/GenericForm';
import adminConfig from 'config/admin';
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 {
    detail,
    addData,
    loadData,
    editData,
    searchData,
    history,
    match: { params },
  } = props;

  const options = adminConfig?.adminSettings[params.resource];

  function submit(val) {
    let data = val;
    if (options.treatData) {
      data = options.treatData(val);
    }

    if (params.id) {
      editData({
        data,
        id: params.id,
        options,
        callback: () => history.goBack(),
      });
    } else {
      addData({
        data,
        options,
        callback: () => history.goBack(),
      });
    }
  }

  useEffect(() => {
    if (params.id) {
      if (!detail || !detail.data) {
        loadData({
          options,
          apiInput: { id: params.id },
        });
      }
      if (detail && detail.data && detail.data._id !== params.id) {
        loadData({
          options,
          apiInput: { id: params.id },
        });
      }
    }
  }, [params]);

  return (
    <div className={styles('Manage')}>
      {(!params.id || detail?.data) && (
        <Form
          component={GenericForm}
          mutators={{ ...arrayMutators }}
          withHeader
          displayId
          title={params.id ? detail?.data?.key || options.editTitle : options.addTitle}
          initialValues={params.id && detail?.data}
          fields={options.model}
          resourceData={detail && detail.data}
          onSubmit={submit}
          fieldsProps={{
            select: {
              loadApiData: searchData,
              apollo: true,
            },
          }}
        />
      )}
    </div>
  );
};

export default Manage;
