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

const getOptionLabel = (item: any, filter: Filter) => {
  const value = _.get(item, filter.as || filter.key);
  return filter.transform ? filter.transform(value) : value;
};

const ServiceList: React.FC = () => {
  const service = useContext(ServiceContext);
  const history = useHistory();
  const location = useLocation();
  const query = useQuery();
  const { data } = hooks[service.route].useList(location.search);
  const { data: unfilteredData } = hooks[service.route].useList('', { revalidateOnMount: !!location.search });

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

  const filters = service.filters?.map(filter => {
    const options = _
      .uniqBy(unfilteredData, filter.key)
      .map((item: any) => ({
        key: _.get(item, filter.key),
        label: getOptionLabel(item, filter),
      }));

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

    const value = _.get(query, filter.key);

    return { ...filter, options, value };
  });

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

    history.push(route);
  };

  const applyFilter = (key: string, value: string) => {
    const updatedQuery = { ...query, [key]: value };
    if (value === '-') delete updatedQuery[key];

    const queryString = new URLSearchParams(updatedQuery);
    history.push(`${service.route}?${queryString}`);
  };

  const resetFilters = () => history.push(service.route);

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

export default ServiceList;
