import React, { memo, useCallback, useContext } from 'react';
import { Undefinable } from 'tsdef';
import { SRow } from '../../common/s-components/layout/s-row';
import { Icon } from '../../common/components/icon';
import { theme } from '../../app/theme';
import { SH6 } from '../../common/s-components/typography/s-h6';
import { SBox } from '../../common/s-components/layout/s-box';
import { fp as _ } from '../../common/utils/fp';
import { NSelect, TVendor } from '../../common/types';
import { AnimatedGradient } from '../../common/components/animated-gradient';
import { getCustomRangeEntity } from '../../common/transducers';
import { ContextStreamLatestDate } from '../../common/context';
import { Flag } from '../../common/components/flag';
import { ACTIVE_TAB } from '../../playlists/constants';
import { TOP_MARKETS_AS_STRING } from '../../market-selector/constants';

type TProps = {
  options: NSelect.TOption[];
  value: NSelect.TValue;
  dateRange: number;
  variant?: 'dark' | 'light';
  market?: Undefinable<string> | null;
  playlistVendor?: TVendor;
  activeOption?: string;
  activeTab?: keyof typeof ACTIVE_TAB;
  hideStreams?: boolean;
  marketCodePlaylistStreams?: string;
};

export const SortBlock: React.FC<TProps> = memo(props => {
  const renderSkeleton = useCallback(() => {
    return (
      <SBox position="relative" overflow="hidden">
        <SBox width={128} height={16} bg={theme.colors.eastBay} />
        <SBox position="absolute" top={0} left={0} height="100%" flex={1}>
          <AnimatedGradient angle={8} gradientWidth={160} />
        </SBox>
      </SBox>
    );
  }, []);

  const {
    options,
    value,
    dateRange,
    variant,
    market,
    playlistVendor,
    activeOption,
    hideStreams,
  } = props;
  const {
    streamLatestDateEntitySpotify,
    streamLatestDateEntityApple,
    streamLatestDateEntityAmazon,
  } = useContext(ContextStreamLatestDate);

  const entity = {
    amazon: streamLatestDateEntityAmazon,
    apple: streamLatestDateEntityApple,
    spotify: streamLatestDateEntitySpotify,
  }[playlistVendor as TVendor];

  const loading = _.path('loading', entity);
  const error = _.path('error', entity);
  const data = _.path('data', entity);
  const formatted = data
    ? getCustomRangeEntity(dateRange, data).standard
    : 'N/A';
  const color =
    variant === 'dark' ? theme.colors.periwinkleGray : theme.colors.white;
  const title =
    (playlistVendor === 'apple' || playlistVendor === 'amazon') &&
    market === TOP_MARKETS_AS_STRING
      ? 'OWNER STR,'
      : 'Streams,';
  const hasOneOption = _.length(options) === 1;
  const activeLabel = _.path(
    'label',
    _.find(_.propEq('value', activeOption))(options)
  );

  return (
    <SRow
      mt={11}
      mb={4}
      px={16}
      alignItems="center"
      justifyContent="space-between"
      height={16}
    >
      <SRow alignItems="center" flex={1} mr={16}>
        <Icon name="sort" color={color} size={12} mr={8} />
        <SBox flex={1} flexShrink={1}>
          <SH6 color={color} numberOfLines={1}>
            {_.isNil(activeOption) && hasOneOption
              ? _.o(_.path('label'), _.find({ value }))(options)
              : activeLabel}
          </SH6>
        </SBox>
      </SRow>
      <SBox>
        {loading && !error && !data ? renderSkeleton() : null}
        {data && !hideStreams ? (
          <SRow alignItems="center">
            {_.isNotNil(market) && market !== TOP_MARKETS_AS_STRING ? (
              <Flag
                market={market}
                width={16}
                height={16}
                marginTop={0}
                variant="white"
              />
            ) : null}
            <SH6 ml={7} mr={1} color={color}>
              {`${title} ${formatted}`}
            </SH6>
          </SRow>
        ) : null}
      </SBox>
    </SRow>
  );
});

SortBlock.defaultProps = {
  variant: 'dark',
  hideStreams: false,
};
