import React, { memo, useContext } from 'react';
import { SBox } from '../../common/s-components/layout/s-box';
import { SH2 } from '../../common/s-components/typography/s-h2';
import { SText } from '../../common/s-components/typography/s-text';
import { ContextDemographics } from '../contexts';
import { TContextDemographics } from '../types';
import { SkeletonTitle } from './skeleton-title';
import { SkeletonDemographics } from './skeleton-demographics';
import { fp as _ } from '../../common/utils/fp';
import { getGender, getAge } from '../transducers';
import { ContextAllVideo } from '../../youtube/contexts';
import { SINGLE_VARIANT } from '../../youtube/constants';
import { SDemographicsContainer } from '../s-components/s-demographics-container';

export const Demographics = memo(() => {
  const props: TContextDemographics = useContext(ContextDemographics);
  const { entity } = props;
  const { loading, error, data } = entity;
  const { youtubeVariant } = useContext(ContextAllVideo);
  const gender = _.path('gender_most_popular', data);
  const age = _.path('age_band_most_popular', data);
  const ageInfo = `${getGender(gender)} aged ${age && getAge(age)}`;
  const noData = data && _.isNull(age);
  const ageTitle = noData ? 'N/A' : ageInfo;
  const startText =
    youtubeVariant === SINGLE_VARIANT ? ' This video is' : 'All videos are';

  return (
    <SDemographicsContainer loading={loading}>
      {loading ? (
        <SBox mt={-2} alignItems="center" mb={24}>
          <SkeletonTitle />
          <SkeletonDemographics />
        </SBox>
      ) : (
        <>
          {error ? (
            <SText mt={12} mb={21} textAlign="center">
              Demographic data failed to load.
            </SText>
          ) : (
            <SText textAlign="center" color="periwinkleGray" mb={10}>
              {`${startText} most popular among`}
            </SText>
          )}
          {data ? <SH2 textAlign="center">{ageTitle}</SH2> : null}
        </>
      )}
    </SDemographicsContainer>
  );
});
