import React, { memo, useContext } from 'react';
import { SBox } from '../../common/s-components/layout/s-box';
import { SText } from '../../common/s-components/typography/s-text';
import { ContextInsight } from '../contexts';
import { TContextInsight } from '../types';
import { fp as _ } from '../../common/utils/fp';
import {
  formatStream,
  formatYearDate,
  pluralize,
} from '../../common/transducers';
import { STextInsight } from '../s-components/s-text-insight';
import { SCreations } from '../s-components/s-creations';
import { SViews } from '../s-components/s-views';
import { SDataContainer } from '../s-components/s-data-container';
import { SErrorContainer } from '../s-components/s-error-container';
import { Skeleton } from './skeleton';
import { SSkeletonContainer } from '../s-components/s-skeleton-container';

export const Insight = memo(() => {
  const props: TContextInsight = useContext(ContextInsight);
  const { entity, visibility, refresh: globalRefresh } = props;
  const { skeleton, error } = visibility;
  const creations = _.path('data.creations', entity);
  const views = _.path('data.views', entity);
  const peakDate = formatYearDate(_.path('data.peak_date', entity));

  if (skeleton && !globalRefresh) {
    return (
      <SSkeletonContainer>
        <Skeleton />
      </SSkeletonContainer>
    );
  }

  if (error) {
    return (
      <SErrorContainer>
        <SText>Peak сreations data failed to load.</SText>
      </SErrorContainer>
    );
  }

  return (
    <SDataContainer>
      <SBox mb={9}>
        <STextInsight>
          This track had{'  '}
          <SCreations color="periwinkleGray">
            {formatStream(creations)} {pluralize('creation', creations)}
          </SCreations>
        </STextInsight>
      </SBox>
      <SBox mb={11}>
        <STextInsight>at its two-week peak on {peakDate},</STextInsight>
      </SBox>
      <STextInsight>
        driving{' '}
        <SViews>
          {formatStream(views)} {pluralize('view', views)}
        </SViews>
      </STextInsight>
    </SDataContainer>
  );
});
