import React, { useContext, memo } from 'react';
import { Animated, Pressable, Dimensions } from 'react-native';
import { useRoute } from '@react-navigation/native';
import { SBoxAnimated } from '../../../common/s-components/layout/s-box-animated';
import { theme } from '../../../app/theme';
import { BackButton } from '../../../common/components/back-button';
import { Router } from '../../../common/utils/navigation-service';
import {
  addSafeArea,
  getStatusBarHeight,
  isRouteInCamel,
  getAnimations,
} from '../../../common/transducers';
import { ContextHeader } from '../../context';
import { fp as _ } from '../../../common/utils/fp';
import { Icon } from '../../../common/components/icon';
import { SRow } from '../../../common/s-components/layout/s-row';
import { TPlaylist } from '../../../common/submodules/starring-playlists/types';
import { StarredBtn } from '../../../track/components/starred/starred-btn';
import { SPlaylistName } from '../../s-components/s-playlist-name';
import {
  goToPlacement,
  navHistoryCache,
} from '../../../playlist-placement/services';
import { ROUTES } from '../../../app/constants';

const { width: DEVICE_WIDTH } = Dimensions.get('window');
const maxHeight = addSafeArea(62);
const minHeight = addSafeArea(52);
const safeArea = getStatusBarHeight();
const heightDiff = maxHeight - minHeight;

type TProps = {
  animationY: Animated.Value;
  scrollToTop: Function;
  toggleStarred: (playlist?: TPlaylist) => void;
};

const Animation = getAnimations({
  titleSmall: {
    opacity: {
      inputRange: [0, heightDiff / 2, heightDiff],
      outputRange: [0, 0, 1],
    },
    translateY: {
      inputRange: [0, heightDiff],
      outputRange: [safeArea + 20, safeArea + 11],
    },
  },

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

  star: {
    translateY: {
      inputRange: [0, heightDiff],
      outputRange: [safeArea + 11, safeArea],
    },
    translateX: -16,
  },

  headerBg: {
    opacity: {
      inputRange: [0, heightDiff],
      outputRange: [0, 1],
    },
    translateY: {
      inputRange: [0, heightDiff],
      outputRange: [0, -heightDiff],
    },
  },
});

export const Header = memo((params: TProps) => {
  const props = useContext(ContextHeader);
  const route = useRoute();

  const {
    entity,
    playlistVisibility,
    tracklistVisibility,
    vendor,
    offline,
  } = props;
  const { animationY, scrollToTop, toggleStarred } = params;
  const playlistName = _.path('data.name', entity);
  const starred = _.path('data.starred', entity);

  const anyOffline =
    offline ||
    _.path('offline', playlistVisibility) ||
    _.path('offline', tracklistVisibility);
  const playlistError = _.path('error', playlistVisibility);

  const goBack = () => {
    const { scrollToTop } = params;

    const lastHistory = navHistoryCache.last();

    // if we have something in history
    if (lastHistory) {
      // if we have previous playlist in last history step
      // it means that after clicking close icon playlist will be just updated and not removed
      if (
        isRouteInCamel(
          ROUTES.playlist,
          _.path(['routing', 'next', 'routeName'], lastHistory)
        )
      ) {
        setTimeout(() => {
          scrollToTop(true);
        }, 32);
      }

      return setTimeout(() => {
        goToPlacement();
      });
    }

    return Router.goBack();
  };

  return (
    <>
      {!anyOffline && !playlistError ? (
        <>
          <SBoxAnimated
            style={Animation.headerBg(animationY)}
            height={maxHeight}
            bg={theme.colors.vulcan}
            position="absolute"
            width={1}
          />

          {!playlistVisibility.skeleton ? (
            <SBoxAnimated
              style={Animation.titleSmall(animationY)}
              width={1}
              position="absolute"
              alignItems="center"
            >
              <Pressable onPress={() => scrollToTop()}>
                {({ pressed }) => (
                  <SRow
                    width={DEVICE_WIDTH - 150}
                    justifyContent="center"
                    opacity={pressed ? 0.7 : 1}
                  >
                    <Icon
                      mt={1}
                      ml={-1}
                      mr={8}
                      name={vendor}
                      color="white"
                      size={22}
                    />
                    <SPlaylistName numberOfLines={1} ellipsizeMode="tail">
                      {playlistName}
                    </SPlaylistName>
                  </SRow>
                )}
              </Pressable>
            </SBoxAnimated>
          ) : null}

          <SBoxAnimated
            style={[Animation.star(animationY)]}
            position="absolute"
            right={0}
            zIndex={10}
          >
            <StarredBtn
              onPress={() => toggleStarred(entity!.data)}
              starred={starred}
              entityVisibility={playlistVisibility}
            />
          </SBoxAnimated>
        </>
      ) : null}
      <SBoxAnimated style={[Animation.arrow(animationY)]} position="absolute">
        <BackButton
          testID="playlist-back-button"
          iconName={
            _.path('gesturesDisabled', route.params) ? 'close' : undefined
          }
          onPress={goBack}
          fixed
        />
      </SBoxAnimated>
    </>
  );
});
