import React, { useContext, useState, memo } from 'react';
// import { LinearGradient } from 'expo-linear-gradient';
import { Swipeable as GSwipeable } from 'react-native-gesture-handler';
import {
  Animated,
  Keyboard,
  TouchableWithoutFeedback,
  // StyleSheet,
  Platform,
} from 'react-native';
import { SBoxAnimated } from '../s-components/layout/s-box-animated';
import { SBox } from '../s-components/layout/s-box';
import { SRow } from '../s-components/layout/s-row';
import { SCol } from '../s-components/layout/s-col';
import { SText } from '../s-components/typography/s-text';
import { SH3 } from '../s-components/typography/s-h3';
import { EStarSourcePages, PLAYLIST_CARD_HEIGHT } from '../constants';
import { theme } from '../../app/theme';
import { Image } from './image';
import { SPersonalizedLabel } from '../s-components/s-personalized-label';
import { SH6 } from '../s-components/typography/s-h6';
import { Icon } from './icon';
import { fp as _ } from '../utils/fp';
import { SSwipeableIcon } from '../s-components/s-swipeable-icon';
import { SRectButton } from '../s-components/s-rect-button';
import { blurSubject$ } from '../utils/input-service';
import { ContextStarredPlaylists } from '../context';
import { toasterSubject$ } from '../submodules/toaster/services/toaster-service';
import { TPlaylist } from '../submodules/starring-playlists/types';
import { StarredIcon } from './starred-icon';
import { Flag } from './flag';

import { EToastTemplate } from '../submodules/toaster/types';

type TProps = TPlaylist & {
  cardHeight: number;
  variant: string;
  keyComposed: string;
  onPress?: (params: TPlaylist) => void;
  onPressRight?: (params: TPlaylist) => void;
  onSwipeableRightWillOpen?: (value: string) => void;
  forwardedRef: any;
  starred?: boolean;
  showStarred?: boolean;
  onRightOpen?: (value: string) => void;
  onRightClose?: (value: string) => void;
  optimistic?: boolean;
  starSource: string;
};

export const SwipeablePlaylistItemComponent: React.FC<TProps> = memo(
  (props: TProps) => {
    const [pressed, setPressed] = useState(false);
    const [pressedBtn, setPressedBtn] = useState(false);
    const { error, offline } = useContext(ContextStarredPlaylists);

    const renderRightActions = (
      progress: Animated.AnimatedInterpolation<any>
    ) => {
      const { variant, starred, onPressRight, ...rest } = props;
      const trans = progress.interpolate({
        inputRange: [0, 1],
        outputRange: [72, 0],
      });

      const iconColor =
        starred && variant === 'dark'
          ? theme.colors.wildStrawberry
          : theme.colors.white;

      return (
        <SRow width={72}>
          <SBoxAnimated style={{ transform: [{ translateX: trans }] }}>
            <TouchableWithoutFeedback
              testID="swipeable-star"
              onPress={() => {
                if (_.isNotNil(rest.optimistic)) return;
                const data = _.omit([
                  'onPress',
                  'onSwipeableRightWillOpen',
                  'forwardedRef',
                  'onRightOpen',
                  'onRightClose',
                ])(rest) as TPlaylist;
                // TODO add new toast variant for playlist
                // TODO add new toast variant for playlist
                // TODO add new toast variant for playlist
                if (error || offline) {
                  toasterSubject$.next({
                    template: EToastTemplate.starLoadError,
                  });
                  return;
                }
                onPressRight!({ ...data });
              }}
              onPressIn={() => {
                setPressedBtn(true);
              }}
              onPressOut={() => {
                setPressedBtn(false);
              }}
            >
              <SRectButton height={PLAYLIST_CARD_HEIGHT}>
                <SSwipeableIcon
                  name={starred ? 'star' : 'star-outlined'}
                  size={31}
                  color={iconColor}
                  opacity={pressedBtn ? 0.7 : 1}
                />
              </SRectButton>
            </TouchableWithoutFeedback>
          </SBoxAnimated>
        </SRow>
      );
    };

    const {
      cardHeight,
      name,
      variant,
      image_url,
      owner,
      personalized,
      vendor,
      keyComposed,
      onSwipeableRightWillOpen,
      forwardedRef,
      onRightOpen,
      onRightClose,
      onPress,
      showStarred,
      starred,
      country_code,
      starSource,
    } = props;

    const bgItem =
      variant === 'dark' ? theme.colors.fiord : theme.colorsRgba.item;
    const bgItemPressed =
      variant === 'dark'
        ? theme.colors.pickledBluewood
        : theme.colorsRgba.itemPressed;
    const pictureHolderGradient =
      variant === 'dark'
        ? theme.gradients.pictureHolderDark
        : theme.gradients.pictureHolderLight;
    const nameMr =
      starSource === EStarSourcePages.Starred && Platform.OS === 'android'
        ? 50
        : 42;

    return (
      <SBox height={cardHeight} pt={16} position="relative">
        <GSwipeable
          onSwipeableRightWillOpen={() =>
            onSwipeableRightWillOpen!(keyComposed)
          }
          onSwipeableRightOpen={() => {
            if (onRightOpen) {
              onRightOpen(keyComposed);
            }
            Keyboard.dismiss();
            blurSubject$.next();
          }}
          onSwipeableClose={() => {
            if (onRightClose) {
              onRightClose(keyComposed);
            }
          }}
          containerStyle={{
            borderTopRightRadius: 8,
            borderBottomRightRadius: 8,
          }}
          ref={forwardedRef}
          friction={2}
          rightThreshold={5}
          renderRightActions={renderRightActions}
          overshootRight={false}
        >
          <TouchableWithoutFeedback
            onPress={() => {
              const data = _.omit([
                'onPress',
                'onSwipeableRightWillOpen',
                'forwardedRef',
                'onRightOpen',
                'onRightClose',
              ])(props) as TPlaylist;
              // if (vendor !== 'amazon') {
              onPress!(data);
              // }
            }}
            onPressIn={() => {
              // if (vendor === 'amazon') return;
              setPressed(true);
            }}
            onPressOut={() => {
              // if (vendor === 'amazon') return;
              setPressed(false);
            }}
          >
            <SBox position="relative" mx={16}>
              <SRow
                height={PLAYLIST_CARD_HEIGHT}
                backgroundColor={pressed ? bgItemPressed : bgItem}
                borderRadius={8}
              >
                {/*{vendor === 'amazon' ? (*/}
                {/*  <LinearGradient*/}
                {/*    colors={theme.gradients.playlistPlacementTrackCard}*/}
                {/*    locations={[0, 0.43, 1]}*/}
                {/*    style={[*/}
                {/*      StyleSheet.absoluteFill,*/}
                {/*      { borderRadius: 8, flex: 1 },*/}
                {/*    ]}*/}
                {/*  />*/}
                {/*) : null}*/}
                <SCol
                  overflow="hidden"
                  style={{
                    borderRadius: 8,
                    borderBottomRightRadius: 0,
                    borderTopRightRadius: 0,
                  }}
                >
                  <Image
                    height={PLAYLIST_CARD_HEIGHT}
                    width={PLAYLIST_CARD_HEIGHT}
                    imageUrl={image_url}
                    bgColors={pictureHolderGradient}
                  />
                </SCol>
                <SCol
                  flex={1}
                  mt={-5}
                  ml={16}
                  mr={nameMr}
                  justifyContent="center"
                >
                  <SH3 numberOfLines={1} testID="swipeable-playlist-name">
                    {_.isNil(name) ? 'N/A' : name}
                  </SH3>
                  {owner ? (
                    <SRow alignItems="center" mt={2}>
                      <SBox flexShrink={1}>
                        <SText
                          numberOfLines={1}
                          testID="swipeable-playlist-owner"
                        >
                          By&nbsp;{owner}
                        </SText>
                      </SBox>
                      {personalized ? (
                        <SPersonalizedLabel
                          ml={4}
                          mt={2}
                          testID="swipeable-playlist-personalized"
                        >
                          <SH6>P</SH6>
                        </SPersonalizedLabel>
                      ) : null}
                    </SRow>
                  ) : null}
                </SCol>
                {starSource === EStarSourcePages.Starred ? (
                  <SRow
                    position="absolute"
                    right={3}
                    bottom={3}
                    alignItems="center"
                  >
                    <SBox left={6}>
                      <Flag
                        market={country_code}
                        width={16}
                        height={16}
                        marginTop={0}
                        variant="light"
                      />
                    </SBox>
                    <SBox>
                      <SBox
                        width={20}
                        height={20}
                        bg="fiord"
                        position="absolute"
                        top={1}
                        left={1}
                        borderRadius={10}
                      />
                      <Icon name={vendor} size={22} color="white" />
                    </SBox>
                  </SRow>
                ) : null}
                {starSource !== EStarSourcePages.Starred ? (
                  <SBox position="absolute" right={3} bottom={3}>
                    <Icon name={vendor} size={22} color="white" />
                  </SBox>
                ) : null}
              </SRow>
              {showStarred && starred ? <StarredIcon /> : null}
            </SBox>
          </TouchableWithoutFeedback>
        </GSwipeable>
      </SBox>
    );
  }
);

SwipeablePlaylistItemComponent.defaultProps = {
  onPress: _.noop,
  onPressRight: _.noop,
  onSwipeableRightWillOpen: _.noop,
  onRightOpen: _.noop,
  onRightClose: _.noop,
};

function forwardRef(props: any, ref: any) {
  return <SwipeablePlaylistItemComponent {...props} forwardedRef={ref} />;
}

export const SwipeablePlaylistItem = React.forwardRef(forwardRef);
