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 list from 'store/list';
import CustomFixedTable from 'components/enhancers/CustomFixedTable';
import TableListItem from 'components/listItems/TableListItem';
import GenericFiltersForm from 'components/forms/GenericFiltersForm';

import options from 'config/adminList';
import ModuleButton from 'components/items/ModuleButton';
import config from 'config/general';
import find from 'lodash/find';
import styleIdentifiers from './listing.scss';

const EnhancedTable = CustomFixedTable(TableListItem, GenericFiltersForm);

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type ListingProps = StateProps & DispatchProps & OwnProps;

const Listing = (props: ListingProps) => {
  const {
    history,
    location: { pathname },
    match: { params },
  } = props;
  // mapStateToProps
  const lg = useSelector((state: StoreState) => state.content.lg);
  const currentList = useSelector((state: StoreState) => state?.list?.list);
  // Allow to dispatch actions
  const dispatch = useDispatch();

  const load = data => dispatch(list.actions.list.request.action(data));
  const resetDetail = () => dispatch(list.actions.detail.reset?.action());

  const loadFunction = values => {
    load({ resourceType: params.resource, data: values });
  };

  const addItem = () => {
    resetDetail();

    // const resource = params.resource;

    if (history) history.push(`${pathname}/create`);
  };

  const renderActions = () => {
    return (
      <div className={styles('buttons')}>
        <ModuleButton
          noMargin
          iconLeft="plus"
          label="New"
          color="primary"
          action={addItem}
          relative
        />
      </div>
    );
  };

  useEffect(() => {
    if (params.resource) {
      loadFunction();
    }
  }, [params.resource]);

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

  return (
    <div className={styles('listing')}>
      {currentList && (
        <EnhancedTable
          virtual
          lg={lg}
          headers={options.headers}
          title={listInfo?.label}
          loading={currentList.loading}
          loaded={currentList.loaded}
          loadFunction={loadFunction}
          actions={renderActions()}
          itemProps={{
            type: params.resource,
            fastDetele: true,
            actionDetail: e => history.push(`${pathname}/${e._id}`),
            actionEdit: e => history.push(`${pathname}/${e._id}/edit`),
          }}
          noMore
          items={currentList.data}
          noCheckbox
        />
      )}
    </div>
  );
};

export default Listing;
