import React, { useContext, memo, useState } from 'react';
import { Animated, TouchableOpacity } from 'react-native';
import { SRow } from '../../common/s-components/layout/s-row';
import { SBox } from '../../common/s-components/layout/s-box';
import { ContextHeader } from '../contexts';
import { SBoxAnimated } from '../../common/s-components/layout/s-box-animated';
import { theme } from '../../app/theme';
import { SH1 } from '../../common/s-components/typography/s-h1';
import { SearchInput } from '../../common/components/search-input';
import { BackButton } from '../../common/components/back-button';
import {
  addSafeArea,
  formatStreamDigit,
  getStatusBarHeight,
  getAnimations,
} from '../../common/transducers';
import { TActiveVisibilityConfig } from '../types';
import { Router } from '../../common/utils/navigation-service';
import { SText } from '../../common/s-components/typography/s-text';
import { Icon } from '../../common/components/icon';
import { ToggleStyled } from '../../common/components/toggle-styled';
import { fp as _ } from '../../common/utils/fp';
import { FETCH_TYPE } from '../../common/constants';
import { ACTIVE_TAB, PLAYLISTS_SORTING_POPUP_ID } from '../constants';
import { openPopupByVariant } from '../../common/utils/keyboard-service';
import { SPageTitleSmall } from '../s-components/s-page-title-small';
import { Touchable } from '../../common/components/touchable';

const maxHeight = addSafeArea(100);
const minHeight = addSafeArea(52);
const safeArea = getStatusBarHeight();
const heightDiff = maxHeight - minHeight;

type TProps = {
  activeVisibility: TActiveVisibilityConfig;
  animationY: Animated.Value;
  scrollToTop: Function;
  onPress: Function;
  isScrolled: boolean;
  isDirtySorting: boolean;
  isFailed: boolean;
  isPressableTitle: boolean;
};

const Animation = getAnimations({
  headerBg: {
    opacity: {
      inputRange: [0, heightDiff],
      outputRange: [0, 1],
    },
    translateY: {
      inputRange: [0, heightDiff],
      outputRange: [0, -heightDiff],
    },
  },

  title: {
    opacity: {
      inputRange: [0, heightDiff / 1.5, heightDiff / 1.5, heightDiff],
      outputRange: [1, 1, 0, 0],
    },
    translateY: {
      inputRange: [0, heightDiff / 1.5, heightDiff / 1.5, heightDiff],
      outputRange: [safeArea + 18, safeArea + 10, safeArea - 80, safeArea - 80],
    },
  },

  titleSmall: {
    opacity: {
      inputRange: [0, heightDiff / 1.5, heightDiff / 1.5, heightDiff],
      outputRange: [0, 0, 1, 1],
    },
    translateY: {
      inputRange: [0, heightDiff / 1.5, heightDiff / 1.5, heightDiff],
      outputRange: [safeArea + 68, safeArea + 68, safeArea + 20, safeArea + 1],
    },
    scaleY: {
      inputRange: [0, heightDiff / 1.5, heightDiff / 1.5, heightDiff],
      outputRange: [0, 0, 1, 1],
    },
  },

  arrow: {
    translateY: {
      inputRange: [0, heightDiff],
      outputRange: [safeArea + 12, safeArea],
    },
    translateX: 17,
  },

  searchBox: {
    translateY: {
      inputRange: [0, heightDiff / 1.5, heightDiff / 1.5, heightDiff],
      outputRange: [safeArea + 92, safeArea + 76, safeArea + 76, -44],
    },
    opacity: {
      inputRange: [0, heightDiff / 1.5, heightDiff / 1.5, heightDiff],
      outputRange: [1, 1, 0, 0],
    },
  },
  input: {
    translateY: 0,
    scaleY: {
      inputRange: [0, heightDiff / 4, heightDiff],
      outputRange: [1, 0, 0],
    },
  },
});

export const Header = memo((params: TProps) => {
  const {
    activeVisibility,
    animationY,
    scrollToTop,
    onPress,
    isDirtySorting,
    isFailed,
    isPressableTitle,
  } = params;
  const { visibility } = activeVisibility;
  const props = useContext(ContextHeader);

  const { config, getData, entityCurrent, entityPast } = props;
  const { vendor, activeTab, currentError, pastError } = config;
  const isLoading =
    activeTab === ACTIVE_TAB.current
      ? entityCurrent.loading
      : entityPast.loading;

  const currentCount = _.path('currentCount', config);
  const pastCount = _.path('pastCount', config);

  const playlistsTotalLoading = _.isNil(currentCount) && _.isNil(pastCount);

  let showPlaylistsSwitcher =
    (activeTab === 'current' && pastCount !== 0) ||
    (activeTab === 'past' && currentCount !== 0);
  if (vendor === 'amazon') {
    showPlaylistsSwitcher = false;
  }

  const inputValue =
    activeTab === ACTIVE_TAB.current
      ? _.path('config.search', entityCurrent)
      : _.path('config.search', entityPast);

  const title =
    activeTab === 'current' ? 'Current Playlists' : 'Past Playlists';

  const isSpotify = vendor === 'spotify';
  const sortingIconBg = isSpotify
    ? theme.colorsRgba.surfieGreenPill
    : vendor === 'apple'
    ? theme.colorsRgba.discoPill
    : theme.colorsRgba.victoria;
  const sortingIconTappedBg = isSpotify
    ? theme.colorsRgba.surfieGreenPillPressed
    : vendor === 'apple'
    ? theme.colorsRgba.discoPillPressed
    : theme.colorsRgba.victoria;

  const cssSortingRules = {
    width: 44,
    height: 44,
    borderRadius: 22,
    pt: 6,
    pl: 6,
    ml: 8,
    opacity: isLoading ? 0.5 : 1,
  };

  const [pressed, setPressed] = useState(false);
  const isAmazon = vendor === 'amazon';

  return (
    <>
      {!visibility.offline &&
      !isFailed &&
      !_.path('offline', currentError) &&
      !_.path('offline', pastError) &&
      !_.path('timeout', currentError) &&
      !_.path('timeout', pastError) ? (
        <>
          <SBoxAnimated
            style={Animation.headerBg(animationY)}
            height={maxHeight}
            bg={theme.colors.vulcan}
            position="absolute"
            width={1}
          />

          <SBoxAnimated
            style={Animation.title(animationY)}
            alignItems="center"
            width={1}
            position="absolute"
            zIndex={2}
          >
            <Touchable
              disabled={isAmazon || !isPressableTitle}
              onPress={() => onPress()}
              togglePress={setPressed}
              touchableOpacityIos
              style={{
                opacity: showPlaylistsSwitcher ? (pressed ? 0.7 : 1) : 1,
              }}
            >
              <SRow alignItems="center">
                {!playlistsTotalLoading ? (
                  <>
                    <SBox>
                      <Icon
                        name={vendor}
                        size={isAmazon ? 31 : 30}
                        color="white"
                        mr={isAmazon ? 8 : 10}
                        mb={isAmazon ? -1 : 0}
                      />
                    </SBox>
                    <SBox>
                      <SH1>{title}</SH1>
                    </SBox>
                    {showPlaylistsSwitcher ? (
                      <SBox ml={9}>
                        <Icon name="down-ind" size={12} color="white" />
                      </SBox>
                    ) : null}
                  </>
                ) : (
                  <SBox mt={7} mb={3}>
                    <SBox width={192} height={16} bg="white" opacity={0.2} />
                  </SBox>
                )}
              </SRow>
              <SRow mt={4} justifyContent="center">
                {!playlistsTotalLoading ? (
                  <>
                    <SBox>
                      <SText fontSize={12} medium>
                        {formatStreamDigit(currentCount as number, {
                          addComma: true,
                        })}{' '}
                        Current
                      </SText>
                    </SBox>
                    {vendor !== 'amazon' ? (
                      <SBox>
                        <SText fontSize={12} medium>
                          ,{' '}
                          {formatStreamDigit(pastCount as number, {
                            addComma: true,
                          })}{' '}
                          Past
                        </SText>
                      </SBox>
                    ) : null}
                  </>
                ) : (
                  <SBox width={80} height={16} bg="white" opacity={0.2} />
                )}
              </SRow>
            </Touchable>
          </SBoxAnimated>

          <SBoxAnimated
            style={[Animation.searchBox(animationY)]}
            width={1}
            position="absolute"
          >
            <SRow mx={16} overflow="hidden">
              <SBoxAnimated flex={1} style={[Animation.input(animationY)]}>
                <SearchInput
                  value={inputValue}
                  placeholder="Find a playlist"
                  searchLoading={_.path(
                    'visibility.skeleton',
                    activeVisibility
                  )}
                  onChange={(search: string) => {
                    getData({ search }, FETCH_TYPE.search);

                    setTimeout(() => {
                      scrollToTop(true);
                    }, 100);
                  }}
                />
              </SBoxAnimated>
              <ToggleStyled
                {...cssSortingRules}
                testID="playlists-toggle"
                defaultCss={{
                  backgroundColor: isDirtySorting
                    ? sortingIconBg
                    : 'transparent',
                }}
                tappedCss={{
                  backgroundColor: isLoading
                    ? 'transparent'
                    : sortingIconTappedBg,
                }}
                onPress={() => {
                  if (isLoading) return false;
                  openPopupByVariant(PLAYLISTS_SORTING_POPUP_ID);
                }}
              >
                <Icon name="filter-sort" color={theme.colors.white} size={32} />
              </ToggleStyled>
            </SRow>
          </SBoxAnimated>

          <SBoxAnimated
            style={Animation.titleSmall(animationY)}
            alignItems="center"
            width={1}
            position="absolute"
          >
            <TouchableOpacity onPress={() => scrollToTop()} activeOpacity={0.7}>
              <SRow alignItems="flex-start" py={10} px={5}>
                {!playlistsTotalLoading ? (
                  <>
                    <SBox mr={9} mt={isSpotify ? 1 : 0}>
                      <Icon name={vendor} size={22} color="white" />
                    </SBox>
                    <SBox>
                      <SPageTitleSmall>{title}</SPageTitleSmall>
                    </SBox>
                  </>
                ) : (
                  <SBox mt={4}>
                    <SBox width={192} height={16} bg="white" opacity={0.2} />
                  </SBox>
                )}
              </SRow>
            </TouchableOpacity>
          </SBoxAnimated>
        </>
      ) : null}
      <SBoxAnimated
        style={[Animation.arrow(animationY), { zIndex: 3 }]}
        position="absolute"
      >
        <BackButton
          testID="all-playlists-back-button"
          onPress={() => Router.goBack()}
          fixed
        />
      </SBoxAnimated>
    </>
  );
});
