import React from 'react';
import { SwipeablePopup } from '../../../common/components/bottom-sheet/swipeable-popup';
import { PopupSelector } from '../../../common/components/popup-selector/popup-selector';
import { fp as _ } from '../../../common/utils/fp';
import { FETCH_TYPE } from '../../../common/constants';
import {
  ORDER_BY,
  SORT_POPUP_ID,
  SORTING_OPTIONS,
  TOP_MARKETS_LABEL,
  TRACK_POSITION_LABEL,
} from '../../constants';
import { TState } from '../../types';
import { NEntityInfinite } from '../../../common/types';
import { onNmfSortingApplied, onHhSortingApplied } from '../../../analytics';

type TProps = {
  config: TState['config'];
  getData: NEntityInfinite.TEntityInfiniteGet;
  setConfig: (config: TState['config']) => void;
  isNmf: boolean;
};

export const SortPopup: React.FC<TProps> = props => {
  const { config, getData, setConfig, isNmf } = props;

  return (
    <>
      <SwipeablePopup
        pb={45}
        fullheight
        variant={SORT_POPUP_ID}
        content={
          <PopupSelector
            id={SORT_POPUP_ID}
            title="Sorting"
            optionsTitle="Sort By"
            options={SORTING_OPTIONS}
            value={_.path('order_by', config)}
            optionsTitleRules={{ mt: 7 }}
            onSubmit={value => {
              setConfig({ order_by: value });
              getData(null, FETCH_TYPE.filter);
              if (isNmf) {
                onNmfSortingApplied({
                  orderBy:
                    value === ORDER_BY.position
                      ? TRACK_POSITION_LABEL
                      : TOP_MARKETS_LABEL,
                });
              } else {
                onHhSortingApplied({
                  orderBy:
                    value === ORDER_BY.position
                      ? TRACK_POSITION_LABEL
                      : TOP_MARKETS_LABEL,
                });
              }
            }}
          />
        }
      />
    </>
  );
};
