import type { ReactElement } from 'react';
import React, { useEffect, useRef } from 'react';
import type { LayoutChangeEvent } from 'react-native';
import { Animated, Easing, Platform } from 'react-native';
import type { BadgeConfigType, SwitchOptionType } from '.';
import { useTheme } from '../../../theme';
import Badge from '../../Badge';
import Icon from '../../Icon';
import Typography from '../../Typography';
import { StyledIconWrapper, StyledTextWrapper } from './StyledSelectorSwitch';

export const OptionContent = ({
  content,
  badge,
}: {
  content: ReactElement;
  badge?: BadgeConfigType;
}) => {
  const theme = useTheme();
  if (!badge) {
    return content;
  }

  if (badge.type === 'status') {
    return (
      <Badge.Status
        visible
        style={{ paddingHorizontal: theme.space.small }}
        testID="selector-switch-status-badge"
      >
        {content}
      </Badge.Status>
    );
  }

  return content;
};

const Option = <T,>({
  text,
  icon,
  badge,
  selected,
  onLayout,
  index = 0,
}: Pick<SwitchOptionType<T>, 'text' | 'icon' | 'badge'> & {
  selected: boolean;
  onLayout?: (e: LayoutChangeEvent) => void;
  index?: number;
}): ReactElement => {
  const animatedValue = useRef(new Animated.Value(1)).current;
  const translateX = animatedValue.interpolate({
    inputRange: [0, 1],
    outputRange: index === 1 ? [-5, 0] : [5, 0],
  });

  useEffect(() => {
    Animated.timing(animatedValue, {
      toValue: selected ? 1 : 0,
      duration: 200,
      easing: Easing.linear,
      useNativeDriver: Platform.OS === 'ios' || Platform.OS === 'android',
    }).start();
  }, [selected]);

  if (selected) {
    return (
      <StyledTextWrapper
        style={{ transform: [{ translateX }] }}
        onLayout={onLayout}
      >
        <OptionContent
          content={<Typography.Body>{text}</Typography.Body>}
          badge={badge}
        />
      </StyledTextWrapper>
    );
  }

  return (
    <StyledIconWrapper
      style={{ transform: [{ translateX }] }}
      onLayout={onLayout}
    >
      <OptionContent content={<Icon icon={icon} />} badge={badge} />
    </StyledIconWrapper>
  );
};

export default Option;
