import React, { useContext } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import _ from 'lodash';
import Page from '../containers/Page';
import ListTable, { Field } from '../components/ListTable';
import hooks from '../hooks/useAPIClient';
import ServiceContext from './ServiceContext';

const getItemField = (item: any, field: Field) => {
  const value = _.get(item, field.key);
  return field.transform ? field.transform(value) : value;
};

const ServiceList: React.FC = () => {
  const service = useContext(ServiceContext);
  const history = useHistory();
  const location = useLocation();
  const { data } = hooks[service.route].useList(location.search);

  const actions = service.actions || [{
    name: 'Добавить',
    route: `/${service.route}/add${location.search}`,
  }];

  const filters = service.filters?.map(key => {
    const field = _.find(service.tableFields, { key });
    if (!field) return { key: '-', label: '-', options: [] };

    const options = data?.map((item: any) => ({
      key: _.get(item, field.key),
      label: getItemField(item, field),
    }));

    // Add default option
    options?.unshift({
      key: '-',
      label: field.label,
    });

    return { ...field, options };
  });

  const handleRowClick = (item: any) => {
    const route = service.rowLink
      ? service.rowLink(item)
      : `/${service.route}/${item?._id}`;

    history.push(route);
  };

  return (
    <Page title={service.name} actions={actions} filters={filters}>
      <ListTable items={data} fields={service.tableFields} handleRowClick={handleRowClick} />
    </Page>
  );
};

export default ServiceList;
