import React, { useEffect, useRef } from 'react';
import { Animated } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { SBox } from '../s-components/layout/s-box';
import { theme } from '../../app/theme';
import { SBoxAnimated } from '../s-components/layout/s-box-animated';
import { getAnimations } from '../transducers';
import { Touchable } from './touchable';

type TProps = {
  checked: boolean;
  onChange: (checked: boolean) => void;
  isLight?: boolean;
};

const inputRange = [0, 1];
const Animation = getAnimations({
  bg: {
    opacity: {
      inputRange,
      outputRange: [0, 1],
    },
  },
  activeCircle: {
    translateX: {
      inputRange,
      outputRange: [2, 22],
    },
    translateY: 2,
  },
  inactiveCircle: {
    opacity: {
      inputRange,
      outputRange: [1, 0],
    },
    translateX: {
      inputRange,
      outputRange: [2, 22],
    },
    translateY: -25,
  },
});

export const Switch: React.FC<TProps> = props => {
  const { checked, onChange, isLight } = props;
  // eslint-disable-next-line react/destructuring-assignment
  const value = useRef(new Animated.Value(checked ? 1 : 0));
  const disabledBg = isLight ? 'lavenderGray' : 'waikawaGray';
  const disabledCircle = isLight ? 'white' : 'lavenderGray';

  const switchOn = () => {
    Animated.timing(value.current, {
      toValue: 1,
      useNativeDriver: true,
      duration: 200,
    }).start();
  };

  const switchOff = () => {
    Animated.timing(value.current, {
      toValue: 0,
      useNativeDriver: true,
      duration: 200,
    }).start();
  };

  useEffect(() => {
    return checked ? switchOn() : switchOff();
  }, [checked]);

  return (
    <Touchable
      onPress={() => {
        onChange(!checked);
      }}
    >
      <SBox
        width={51}
        height={31}
        borderRadius={16}
        bg={disabledBg}
        overflow="hidden"
      >
        <SBoxAnimated
          width={51}
          height={31}
          position="absolute"
          style={[Animation.bg(value.current)]}
        >
          <LinearGradient
            colors={theme.gradients.playlistApple}
            style={{ flex: 1 }}
          />
        </SBoxAnimated>
        <SBoxAnimated
          width={27}
          height={27}
          borderRadius={15}
          bg={theme.colors.white}
          style={[Animation.activeCircle(value.current)]}
        />
        <SBoxAnimated
          width={27}
          height={27}
          borderRadius={15}
          bg={disabledCircle}
          style={[Animation.inactiveCircle(value.current)]}
        />
      </SBox>
    </Touchable>
  );
};
