import React, { memo, useCallback } from 'react';
import { Platform, StyleSheet } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { RefreshableView } from '../../common/components/refreshable-view';
import { theme } from '../../app/theme';
import { ViewLoadFailed } from '../../common/components/view-load-failed';
import { ViewNetworkFailed } from '../../common/components/view-network-failed';
import { SBox } from '../../common/s-components/layout/s-box';
import { addSafeArea } from '../../common/transducers';
import { TAllVideosVisibility } from '../types';
import { TEntityVisibility, TRefreshableRenderer } from '../../common/types';
import { TrackCard } from './track-card/track-card';
import { Header } from './header';
import { fp as _ } from '../../common/utils/fp';
import { SImage } from '../../common/s-components/s-image';
// import { Slider } from './slider/slider';
import TiktokKpi from '../../tiktok-kpi';
import TiktokMarkets from '../../tiktok-markets';
import TiktokInsight from '../../tiktok-insight';
import { RotationOverlay } from '../../common/components/rotation-overlay';
import { Wave } from './wave';
import { TState as TInsightState } from '../../tiktok-insight/types';
// import { AllVideos } from './all-videos/all-videos';
// import { MULTIPLE_VARIANT, SINGLE_VARIANT } from '../constants';
import { TData as TTrackData } from '../../track/types';
import { SWaveMask } from '../s-components/s-wave-mask';
import { SBgImageContainer } from '../s-components/s-bg-image-container';
import { SRow } from '../../common/s-components/layout/s-row';
import { Icon } from '../../common/components/icon';
import { SH1 } from '../../common/s-components/typography/s-h1';
import { ROUTES } from '../../app/constants';

const maxHeight = addSafeArea(20);

type TProps = {
  refreshing: boolean;
  refresh: () => void;
  visibility: TEntityVisibility;
  insight: TInsightState['insight'];
  tiktokVariant: string;
  trackData: TTrackData | {};
  visibilityAllVideos: TAllVideosVisibility;
};

export const Tiktok: React.FC<TProps> = memo(props => {
  const {
    refreshing,
    refresh,
    tiktokVariant,
    visibility,
    trackData,
    visibilityAllVideos,
    insight,
  } = props;
  const renderHeader: TRefreshableRenderer = ({
    animationY,
    scrollToTop /*, isScrolled*/,
  }) => {
    return (
      <Header
        animationY={animationY}
        scrollToTop={scrollToTop}
        tiktokVariant={tiktokVariant}
      />
    );
  };

  const renderBgLayer: TRefreshableRenderer = () => {
    if (visibility.offline || visibility.error || visibilityAllVideos.offline) {
      return null;
    }

    const imageUrl = _.path('image_url', trackData);
    const containerHeight = 375;

    return (
      <SBox position="relative" height={containerHeight}>
        {imageUrl ? (
          <SBgImageContainer opacity={0.4}>
            <SImage
              height={containerHeight}
              width={1}
              alignSelf="center"
              source={{
                uri: imageUrl,
              }}
            />
          </SBgImageContainer>
        ) : null}

        <LinearGradient
          colors={theme.gradients.tiktok4}
          locations={[0, 0.42, 1]}
          style={[
            StyleSheet.absoluteFill,
            { flex: 1, height: containerHeight },
          ]}
        />
        <LinearGradient
          colors={theme.gradients.tiktok3}
          locations={[0, 1]}
          style={[
            StyleSheet.absoluteFill,
            { flex: 1, height: 243, opacity: 0.8, top: -100 },
          ]}
        />
      </SBox>
    );
  };

  const renderBody: TRefreshableRenderer = useCallback(
    ({ animationY }) => {
      const data = _.path('data', insight);
      const noData =
        data && _.isNull(_.path('data.age_band_most_popular', insight));
      const isIos = Platform.OS === 'ios';
      const gradientTopIos = 260;
      const gradientTopAndroid = 232;
      const waveIsShown = data || noData || _.path('error', insight);

      if (visibility.offline || visibilityAllVideos.offline) {
        return (
          <SBox flex={1}>
            <ViewNetworkFailed verticalOffset={6} />
          </SBox>
        );
      }

      if (visibility.error && !visibility.offline) {
        return (
          <SBox flex={1}>
            <ViewLoadFailed verticalOffset={2} />
          </SBox>
        );
      }

      return (
        <>
          <SBox position="relative" flex={1} pt={maxHeight}>
            <TrackCard animationY={animationY} />
            <SBox width={304} alignSelf="center" mt={40} mb={16}>
              <SRow>
                <Icon name="tiktok" size={32} color="white" mr={8} ml={5} />
                <SH1 mt={4}>User Generated Content</SH1>
              </SRow>
            </SBox>
            <LinearGradient
              colors={theme.gradients.trackMarkets}
              locations={[0, 0.55, 1]}
              style={[
                StyleSheet.absoluteFill,
                {
                  flex: 1,
                  height: 123,
                  top: isIos ? gradientTopIos : gradientTopAndroid,
                },
              ]}
            />
            <SBox width={1} height={28} />

            <SBox position="relative">
              <TiktokKpi />
              <TiktokInsight />
              <TiktokMarkets />
              <SWaveMask />
              {waveIsShown ? <Wave topPosition={383} /> : null}
            </SBox>
          </SBox>
        </>
      );
    },
    [visibility, insight, visibilityAllVideos]
  );

  const renderFgLayer2 = () => <RotationOverlay />;

  return (
    <RefreshableView
      loading={refreshing}
      indicatorLight
      indicatorOffsetTop={maxHeight - 20}
      // inifite pagination - get next page when we don't have payload
      // onScrollReachBottom={() => getData('infinite')}
      onPullDown={() => {
        return refresh();
      }}
      renderHeader={renderHeader}
      renderBgLayer={renderBgLayer}
      renderBody={renderBody}
      renderFgLayer2={renderFgLayer2}
      name={ROUTES.tiktok}
      withNativeDriver
    />
  );
});
