import React, { useState, useEffect } from 'react';
import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import adminConfig from 'config/admin';
import ModuleForm from 'components/forms/ModuleForm';
import { Form } from 'react-final-form';
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 },
    location,
  } = props;

  const options = adminConfig?.adminShop?.ressource[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(),
      });
    }
  }

  function getInitialValues() {
    if (params.id) {
      return detail && detail.data;
    }

    if (!params.id && location.state && location.state.initialValues) {
      return location.state.initialValues;
    }

    return {};
  }

  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')}>
      <Form
        component={ModuleForm}
        withHeader
        displayId
        title={params.id ? options.titleEdit : options.titleAdd}
        initialValues={getInitialValues()}
        fields={options.model}
        resourceData={detail && detail.data}
        onSubmit={submit}
        fieldsProps={{
          select: {
            loadApiData: searchData,
            apollo: true,
          },
        }}
      />
    </div>
  );
};

export default Manage;
