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

import options from 'config/adminErrors';
import error from 'store/error';
import ModuleButton from 'components/items/ModuleButton';
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?.error?.list);
  // Allow to dispatch actions
  const dispatch = useDispatch();

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

  const loadFunction = values => {
    load({ data: values });
  };

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

    // const resource = params.resource;

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

  useEffect(() => {
    loadFunction();
  }, []);

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

export default Listing;
