import React, { useState, useEffect } from 'react';

// Redux part
import { useSelector, useDispatch } from 'react-redux';
import { StoreState } from 'store/rootReducer';
import GenericDisplayFields from 'components/pageItems/GenericDisplayFields';

import MosaicStructure from 'components/enhancers/MosaicStructure';

// Import actions here

import classNames from 'classnames/bind';
import { fieldsToList } from 'store/utils/adminHelpers';
import options from 'config/adminList';
import list from 'store/list';
import config, { viewConfig } from 'config/general';
import GenericHeader from 'components/pageItems/GenericHeader';
import styleIdentifiers from './detail.scss';

const GenericStructure = MosaicStructure(GenericDisplayFields);

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type DetailProps = StateProps & DispatchProps & OwnProps;

const Detail = (props: DetailProps) => {
  const {
    history,
    location: { pathname },
    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 deleteItem = data => dispatch(list.actions.delete.request.action(data));

  const deleteCurrent = () => {
    deleteItem({
      id: params.id,
      callback: () => {
        history.goBack();
      },
    });
  };
  useEffect(() => {
    load({
      id: params.id,
    });
  }, [params.id]);

  const listFields = fieldsToList(options.model);

  return (
    <div className={styles('detail', 'header')}>
      {detail?.data && (
        <GenericHeader
          title={detail?.data?.title && detail.data.title[lg]}
          editAction={() => history.push(`${pathname}/edit`)}
          deleteAction={deleteCurrent}
        />
      )}
      <div className={styles('content')}>
        <GenericStructure
          transformedData={options.transformedData}
          scrollableColumns
          minWidth={config.widthDetailColumn}
          data={detail && detail.data}
          items={listFields}
          oneSection={listFields.length === 1}
        />
      </div>
    </div>
  );
};

export default Detail;
