import React, { memo } from 'react';
import { Portal } from '../../../common/utils/portal/portal';
import { SwipeablePopup } from '../../../common/components/bottom-sheet/swipeable-popup';
import { PopupSelector } from '../../../common/components/popup-selector/popup-selector';
import { NEntityInfinite } from '../../../common/types';
import { fp as _ } from '../../../common/utils/fp';
import { FETCH_TYPE } from '../../../common/constants';
import {
  onPlaylistplacementSortClick,
  onPlaylistSortClick,
} from '../../../analytics';
import { SORTING_OPTIONS, TRACKLIST_VARIANT } from '../../constants';
import { TTracklistExtended, TTracklistVariant } from '../../types';

type TProps = {
  data: TTracklistExtended;
  getTracklist: NEntityInfinite.TEntityInfiniteGet;
  sortId: string;
  variant: TTracklistVariant;
};

export const SortPopup: React.FC<TProps> = memo(props => {
  const { data, getTracklist, sortId, variant } = props;

  const params = {
    orderBy: _.path('config.orderBy', data),
  };
  return (
    <>
      <Portal id={sortId} updateIfAnyChanged={params}>
        <SwipeablePopup
          pb={60}
          fullheight
          variant={sortId}
          content={
            <PopupSelector
              id={sortId}
              title="Sorting"
              optionsTitle="Sort By"
              options={SORTING_OPTIONS}
              value={_.path('config.orderBy', data)}
              onSubmit={
                value => {
                  getTracklist({ orderBy: value }, FETCH_TYPE.sort);
                  if (variant === TRACKLIST_VARIANT.playlistPlacement) {
                    onPlaylistplacementSortClick({
                      orderBy: _.compose(
                        _.path('label'),
                        _.find({ value })
                      )(SORTING_OPTIONS),
                    });
                  }
                  if (variant === TRACKLIST_VARIANT.playlist) {
                    onPlaylistSortClick({
                      orderBy: _.compose(
                        _.path('label'),
                        _.find({ value })
                      )(SORTING_OPTIONS),
                    });
                  }
                }
                /*value => {
                  // Alert.alert('sort', value);
                }*/
              }
            />
          }
        />
      </Portal>
    </>
  );
});
