import React, { useContext, memo, useCallback } from 'react';
import { Dimensions } from 'react-native';
import { SBox } from '../../../common/s-components/layout/s-box';
import { showRotationOverlay } from '../../../common/utils/rotation-service';
import { setLandscapeOrientation } from '../../../common/utils/device-utils';
import { Router } from '../../../common/utils/navigation-service';
import { ROUTES } from '../../../app/constants';
import { ContextGraph } from '../../contexts';
import { fp as _ } from '../../../common/utils/fp';
import { LineGraphInner } from '../../../graph/components/line-graph-inner';
import { theme } from '../../../app/theme';
import { SGradientCard } from '../../../common/s-components/s-gradient-card';
import { ShadowBox } from '../../../common/components/shadow-box';
import { SGraphTitle } from '../../../graph/s-components/s-graph-title';
import { Button } from '../../../common/components/button';
import { SContainerButton } from '../../s-components/graph/s-container-button';
import { Empty } from './empty';

export const GraphSmall = memo(() => {
  const onFullScreen = useCallback((): void => {
    showRotationOverlay(() => {
      setLandscapeOrientation();
      Router.goTo(ROUTES.tiktokgraph);
    });
  }, []);

  const { graph, markets } = useContext(ContextGraph);
  const { creations, videoViews } = _.path<any, any>('data', graph) || {};
  const isEmptyCreations = _.path('empty', creations);
  const isEmptyViews = _.path('empty', videoViews);
  const owner = _.path('owner', markets);
  const cardWidth = Dimensions.get('window').width - 32;

  return (
    <SBox testID="tiktok-kpi-graph" mx={16} height={342}>
      <SBox borderRadius={8} flex={1}>
        <ShadowBox
          height="100%"
          bg={theme.colors.eastBay}
          borderRadius={8}
          androidShadowOffset={2}
        >
          <SGradientCard
            colors={theme.gradients.marketCard}
            opacity={0.4}
            width={cardWidth}
            borderRadius={8}
          />
          <SBox px={16} pt={10} pb={15}>
            <SGraphTitle>Creations & Views</SGraphTitle>
          </SBox>
          {isEmptyCreations ? (
            <SBox mt={10} mb={6}>
              <Empty marketCode={owner} variant="creations" />
            </SBox>
          ) : (
            <LineGraphInner
              {...creations}
              title="Creations"
              hideXAxis={!isEmptyViews}
            />
          )}

          {isEmptyViews ? (
            <Empty marketCode={owner} variant="views" />
          ) : (
            <LineGraphInner {...videoViews} title="Views" />
          )}
        </ShadowBox>
      </SBox>

      <SContainerButton>
        <Button
          testID="line-graph-details-button"
          onPress={() => {
            onFullScreen();
          }}
          width={140}
        >
          Details
        </Button>
      </SContainerButton>
    </SBox>
  );
});
