import React, { useState, useEffect, useRef } from 'react';
import classNames from 'classnames/bind';
import CustomFixedTable from 'components/enhancers/CustomFixedTable';
import TableListItem from 'components/listItems/TableListItem';
import ModuleButton from 'components/items/ModuleButton';
import ModuleList from 'components/pageItems/ModuleList';
import ShopCard from 'components/listItems/ShopCard';
import qs from 'query-string';
import { deepOmit } from 'store/utils/helper';
import adminConfig from 'config/admin';
import styleIdentifiers from './list.scss';

const EnhancedTable = CustomFixedTable(TableListItem);

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type ListProps = StateProps & DispatchProps & OwnProps;

const List = (props: ListProps) => {
  const {
    lg,
    loadData,
    deleteItem,
    shop,
    history,
    match: { params },
    location,
    loadOneData,
    orderMarkPaid,
    orderMarkUnPain,
    orderCancel,
    orderReimburse,
  } = props;

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

  const resource = shop && (shop[options.resourceName] || shop[params.resource]);

  const [checked, setChecked] = useState([]);

  function renderActions() {
    return (
      <div className={styles('buttons')}>
        {!options.noCreate && (
          <ModuleButton
            noMargin
            icon="plus"
            color="primary"
            action={() => history.push(`/shop/${params.resource}/add`)}
            relative
          />
        )}
      </div>
    );
  }

  function renderDetailLink(e) {
    history.push(`/shop/${params.resource}/${e._id}`);
  }

  function cloneProduct(e) {
    loadOneData({
      options,
      apiInput: { id: e._id },
      callback: res => {
        history.push({
          pathname: `/shop/${params.resource}/add`,
          state: { initialValues: deepOmit(res, ['_id', '__typename']) },
        });
      },
    });
  }

  function deleteData(elem) {
    deleteItem({
      id: elem._id,
      options,
      resource: params.resource,
    });
  }

  function loadDataPage(inputs) {
    loadData({
      options: {
        ...options,
        inputModel: {
          ...options.inputModel,
          ...inputs,
        },
      },
      resource: params.resource,
    });
  }

  function markAsPaidOrder() {
    if (checked.length !== 0) {
      for (let index = 0; index < checked.length; index++) {
        const id = checked[index];
        orderMarkPaid({ id });
      }
    }
  }

  function markAsUnPaidOrder() {
    if (checked.length !== 0) {
      for (let index = 0; index < checked.length; index++) {
        const id = checked[index];
        orderMarkUnPain({ id });
      }
    }
  }

  function cancelOrder() {
    if (checked.length !== 0) {
      for (let index = 0; index < checked.length; index++) {
        const id = checked[index];
        orderCancel({ id });
      }
    }
  }

  function reimburseOrder() {
    if (checked.length !== 0) {
      for (let index = 0; index < checked.length; index++) {
        const id = checked[index];
        orderReimburse({ id });
      }
    }
  }

  function renderActionList() {
    switch (params.resource) {
      case 'orders':
        return [
          {
            label: 'Mark as paid',
            action: markAsPaidOrder,
          },
          {
            label: 'Mark as unpaid',
            action: markAsUnPaidOrder,
          },
          {
            label: 'Reimburse',
            action: reimburseOrder,
          },
          {
            label: 'Cancel Order',
            action: cancelOrder,
          },
        ];
      default:
        return false;
    }
  }

  const handleChecked = latestChecked => {
    if (!latestChecked || !checked) return;

    if (checked.length !== latestChecked.length) {
      setChecked(latestChecked);
    }
  };

  function renderListMode() {
    const mode = options && options.listMode;
    switch (mode) {
      case 'card':
        return (
          <div className={styles('card-container')}>
            {((resource && resource.data) || []).map((item, key) => (
              <ShopCard
                key={key}
                data={item}
                actions={[
                  {
                    label: 'Edit',
                    action: e => history.push(`/shop/${params.resource}/${e.data._id}/edit`),
                  },
                  {
                    label: 'View',
                    action: e => renderDetailLink(e.data),
                  },
                  {
                    label: 'Clone',
                    action: e => cloneProduct(e.data),
                  },
                  {
                    label: 'Delete',
                    action: e => deleteData(e.data),
                  },
                ]}
              />
            ))}
          </div>
        );
      default:
        return (
          <EnhancedTable
            virtual
            lg={lg}
            headers={(options && options.headers) || []}
            loadFunc={loadDataPage}
            loading={resource && resource.loading}
            loaded={resource && resource.loaded}
            requestData={resource && resource.requestData}
            actions={renderActions()}
            itemProps={{
              actionDetail: e => renderDetailLink(e),
              actionEdit: e => history.push(`/shop/${params.resource}/${e._id}/edit`),
              actionDelete: e => deleteData(e),
              fastDelete: options.deleteMethod,
              noUpdate: options.noUpdate,
            }}
            items={(resource && resource.data) || []}
            options={options}
            handleChecked={handleChecked}
            noCheckbox={params?.resource !== 'orders'}
            noHeader
          />
        );
    }
  }

  const subNav = options && options.subNav;

  useEffect(() => {
    loadDataPage(qs.parse(location.search));
  }, [location]);

  return (
    <ModuleList
      className={styles('List')}
      loadFunc={loadDataPage}
      subNav={subNav}
      actions={renderActionList()}
      options={options}
      noBorderTitle={!options.listMode}
      checked={checked}
    >
      {renderListMode()}
    </ModuleList>
  );
};

export default List;
