import React, { memo, useCallback } from 'react';
import { LinearGradient } from 'expo-linear-gradient';
import { TVisibility } from '../types';
import { Skeleton } from './skeleton';
import { ErrorBlock } from '../../common/components/error-block';
import { togglePopup } from '../../common/utils/swipeable-popup-service';
import { Portal } from '../../common/utils/portal/portal';
import { SwipeablePopup } from '../../common/components/bottom-sheet/swipeable-popup';
import { InfoStreams } from './info-streams';
import { SBox } from '../../common/s-components/layout/s-box';
import { InfoTitle } from '../../common/components/info-title';
import { CardsSlider } from './cards-slider';
import { theme } from '../../app/theme';
import { onInfoIconPress, CLICK_SOURCES } from '../../analytics';
import { TEntity } from '../../common/types';

type TProps = {
  visibility: TVisibility;
  streams: TEntity;
  marketCode: string;
};

export const MarketStreams: React.FC<TProps> = memo(props => {
  const { visibility, streams, marketCode } = props;
  const infoPressHandler = (variant: string): void => {
    togglePopup(variant);
    onInfoIconPress({ source_section: CLICK_SOURCES.STREAMS_OVERVIEW });
  };

  const renderFgLayer = useCallback(() => {
    const params = {
      streams,
      marketCode,
    };
    return (
      <>
        <Portal id="market-streams" updateIfAnyChanged={params}>
          <SwipeablePopup
            variant="track-performance"
            content={<InfoStreams streams={streams} />}
          />
        </Portal>
      </>
    );
  }, [streams, marketCode]);

  return (
    <SBox bg={theme.colors.ebonyClay}>
      <LinearGradient
        colors={theme.gradients.marketStreams}
        style={{
          position: 'absolute',
          left: 0,
          right: 0,
          top: 0,
          height: '100%',
        }}
      />
      {renderFgLayer()}
      {visibility.skeleton ? <Skeleton /> : null}

      {!visibility.skeleton ? (
        <SBox mr={16} ml={16} mb={19}>
          <InfoTitle
            testID="info-title-streams-overview"
            onPress={() => {
              infoPressHandler('track-performance');
            }}
            title="Streams Overview"
          />
        </SBox>
      ) : null}

      {visibility.error ? (
        <ErrorBlock message="Data failed to load." height={160} mb={76} />
      ) : null}

      {visibility.data ? (
        <>
          <SBox mb={54}>
            <CardsSlider />
          </SBox>
        </>
      ) : null}
    </SBox>
  );
});
