import React, { useState, useEffect } from 'react';
import classNames from 'classnames/bind';
import adminConfig from 'config/admin';
import { Switch, Route } from 'react-router-dom';
import ModuleDetailStructure from 'components/enhancers/ModuleDetailStructure';
import ModuleDisplayFields from 'components/pageItems/ModuleDisplayFields';
import { fieldsToList } from 'store/utils/adminHelpers';
import SingleOrder from 'components/routes/Shop/SingleOrder';
import styleIdentifiers from './detail.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type DetailProps = StateProps & DispatchProps & OwnProps;

const GenericStructure = ModuleDetailStructure(ModuleDisplayFields);

const Detail = (props: DetailProps) => {
  const {
    loadData,
    detail,
    history,
    match: { params },
  } = props;

  const options = adminConfig?.adminShop?.ressource[params.resource];

  function renderStructureDetail() {
    if (params.resource === 'orders') {
      return <SingleOrder />;
    }

    return (
      <GenericStructure
        transformedData={options.transformedData}
        scrollableColumns
        minWidth={300}
        title={options.titleDetail}
        data={detail && detail.data}
        items={fieldsToList(options.model)}
        actions={[
          {
            label: 'Edit',
            action: () => history.push(`/shop/${params.resource}/${detail.data._id}/edit`),
          },
        ]}
      />
    );
  }

  useEffect(() => {
    loadData({
      options,
      apiInput: { id: params.id },
    });
  }, [params.id]);

  return (
    <div className={styles('Detail', 'header')}>
      <div className={styles('container')}>
        {detail && detail.data && (
          <div className={styles('content')}>
            <Switch>
              <Route path="/shop/:resource/:id/detail" component={() => renderStructureDetail()} />
              <Route component={() => renderStructureDetail()} />
            </Switch>
          </div>
        )}
      </div>
    </div>
  );
};

export default Detail;
