import React, { useContext, memo } from 'react';
import { ContextPills, ContextViews } from '../../contexts';
import { SRow } from '../../../common/s-components/layout/s-row';
import { SBox } from '../../../common/s-components/layout/s-box';
import { Pill } from '../../../common/components/pill';
import { fp as _ } from '../../../common/utils/fp';
import { Skeleton } from './skeleton';
import { ROUTE_PARAMS, ROUTES } from '../../../app/constants';
import { Router } from '../../../common/utils/navigation-service';
import { MARKET_VARIANT_PARAMS } from '../../../market-selector/constants';
import { MULTIPLE_VARIANT, SINGLE_VARIANT } from '../../../youtube/constants';

export const Pills = memo(() => {
  const props = useContext(ContextPills);
  const { viewsEntity, views } = useContext(ContextViews);
  const isGraphEmpty = _.path('data', views) && _.path('empty', viewsEntity);
  const {
    markets,
    loading,
    refresh,
    youtubeListLoading,
    youtubeParams,
  } = props;
  const youtubeVariant = _.path(ROUTE_PARAMS.youtubeVariant, youtubeParams);
  const showSkeleton =
    ((loading && youtubeVariant === SINGLE_VARIANT) ||
      (youtubeListLoading && youtubeVariant === MULTIPLE_VARIANT)) &&
    !refresh;
  const owner = _.path('owner', markets);
  const marketVariant =
    youtubeVariant === SINGLE_VARIANT
      ? MARKET_VARIANT_PARAMS.youtubeVideo
      : MARKET_VARIANT_PARAMS.youtubeAllVideos;

  let pillLabel = '';
  let marketCode = '';
  pillLabel = owner === 'all' ? 'All markets' : '';
  marketCode = owner === 'all' ? 'empty' : owner;

  return (
    <>
      {showSkeleton ? (
        <SBox pb={28}>
          <Skeleton />
        </SBox>
      ) : null}

      {!showSkeleton ? (
        <SRow px={16} pb={28}>
          <Pill
            label={pillLabel}
            marketCode={marketCode}
            marketNameVariant="short_name"
            flagMarginTop={1}
            onPress={() => {
              Router.goTo(ROUTES.marketselector, {
                [ROUTE_PARAMS.marketVariant]: marketVariant,
                [ROUTE_PARAMS.marketCodeYoutube]: owner,
              });
            }}
            disabled={isGraphEmpty}
          />
        </SRow>
      ) : null}
    </>
  );
});
