import React, { memo, useContext } from 'react';
import { Animated, Platform } from 'react-native';
import { SBoxAnimated } from '../../../common/s-components/layout/s-box-animated';
import { SAvatar } from '../../../common/s-components/s-avatar';
import { ImgTemplate } from '../../../common/components/img-template';
import { Skeleton } from './skeleton';
import { SBox } from '../../../common/s-components/layout/s-box';
import { fp as _ } from '../../../common/utils/fp';
import {
  ContextStatics,
  ContextTrack,
  ContextVisibility,
} from '../../contexts';
import { addSafeArea, getAnimations } from '../../../common/transducers';
import { Icon } from '../../../common/components/icon';
import { DistributorIcon } from '../../../common/components/distributor-icon';
import { SAvatarImageContainer } from '../../s-components/s-avatar-image-container';

type TProps = {
  animationY: Animated.Value;
};

const maxHeight = addSafeArea(88);
const minHeight = addSafeArea(54);
const heightDiff = maxHeight - minHeight;

const Animation = getAnimations({
  avatar: {
    opacity: {
      inputRange: [0, heightDiff],
      outputRange: [1, 0],
    },
  },
});

export const Avatar: React.FC<TProps> = memo(props => {
  const { visibility } = useContext(ContextVisibility);
  const { track } = useContext(ContextTrack);
  const { distributor } = useContext(ContextStatics);
  const { data } = track;
  const isAndroid = Platform.OS === 'android';

  const { animationY } = props;
  const image_url = _.path('image_url', data);

  if (visibility.track.skeleton) return <Skeleton />;

  if (visibility.track.error || visibility.offline) return null;

  return (
    <SBoxAnimated
      mt={isAndroid ? -30 : 0}
      style={Animation.avatar(animationY)}
      alignItems="center"
      px={21}
      height={137}
      position="relative"
    >
      <ImgTemplate position="absolute" top={9} />
      <SAvatarImageContainer>
        {image_url ? <SAvatar source={{ uri: image_url }} /> : null}
        {distributor ? (
          <SBox position="absolute" bottom={0}>
            <DistributorIcon variant={distributor} />
          </SBox>
        ) : null}
      </SAvatarImageContainer>
      <Icon size={11} name="down-ind" color="white" mt={8} ml={1} />
    </SBoxAnimated>
  );
});
