import {useNavigation} from '@react-navigation/native';
import React, {useEffect, useState} from 'react';
import {Image, StyleSheet} from 'react-native';
import {TouchableOpacity} from 'react-native-gesture-handler';
import LinearGradient from 'react-native-linear-gradient';
import Animated, {Easing} from 'react-native-reanimated';
import {UniversityBadge} from 'src/types';
import {UniversityIcon} from '..';
import {normalize, SCREEN_WIDTH} from '../../utils';
import UniversityIconClicked from './UniversityIconClicked';
interface BadgesDropdownProps {
  localBadges: {
    badge: UniversityBadge;
    img: string;
  }[];
  badges: UniversityBadge[];
}

const BadgesDropdown: React.FC<BadgesDropdownProps> = ({
  localBadges,
  badges,
}) => {
  // Used to toggle between dropdown being displayed and not
  const [displayBadges, setDisplayBadges] = useState<boolean>(false);

  // Determines the absolute position of the individual badges [0, i * 40]
  let [top, setTop] = useState<Animated.Value<number>[]>([]);
  const navigation = useNavigation();

  useEffect(() => {
    // Initialize position of badges to 0
    const defineBadgePositions = () => {
      let localTop: Animated.Value<number>[] = [];
      badges.forEach(() => {
        localTop.push(new Animated.Value(0));
      });
      setTop(localTop);
    };
    defineBadgePositions();
  }, []);

  // Displays badges dropdown by updating top [state] for every badge
  const animate = () => {
    for (let i = 0; i < badges?.length; i++) {
      if (top) {
        Animated.timing(top[i], {
          toValue: i * 40 + 50,
          duration: 150,
          easing: Easing.linear,
        }).start();
      }
    }
  };

  // Draws back displayed badges by setting top [state] to 0 for every badge
  const animateBack = () => {
    for (let i = 0; i < badges?.length; i++) {
      if (top) {
        Animated.timing(top[i], {
          toValue: 0,
          duration: 150,
          easing: Easing.linear,
        }).start();
      }
    }
  };

  return (
    <Animated.View
      style={[styles.badgesContainer, {height: 50 + 40 * localBadges.length}]}>
      <TouchableOpacity
        activeOpacity={1}
        onPress={() => {
          const updatedBadges = !displayBadges;
          setDisplayBadges(updatedBadges);
          if (updatedBadges) {
            animate();
          } else {
            animateBack();
          }
        }}>
        {displayBadges ? (
          <UniversityIconClicked
            university="brown"
            style={styles.universityIconContainer}
            imageStyle={{width: normalize(31), height: normalize(38)}}
          />
        ) : (
          <UniversityIcon
            university="brown"
            style={styles.universityIconContainer}
            imageStyle={{width: normalize(31), height: normalize(38)}}
          />
        )}
      </TouchableOpacity>
      {localBadges &&
        localBadges.map(({badge, img}, index) => (
          <Animated.View
            key={badge.id}
            style={[
              styles.animatedBadgeView,
              {
                top: top[index],
                zIndex: -1 * badge.id,
              },
            ]}>
            <TouchableOpacity
              style={styles.badgeButton}
              onPress={() => {
                navigation.navigate('MutualBadgeHolders', {
                  badge_id: badge.id,
                  badge_title: badge.name,
                  badge_img: img,
                });
              }}>
              <LinearGradient
                colors={['#4E3629', '#EC2027']}
                useAngle={true}
                angle={154.72}
                angleCenter={{x: 0.5, y: 0.5}}
                style={styles.badgeBackground}>
                <Image
                  source={img}
                  style={{
                    width: SCREEN_WIDTH * 0.04,
                    height: SCREEN_WIDTH * 0.04,
                  }}
                />
              </LinearGradient>
            </TouchableOpacity>
          </Animated.View>
        ))}
    </Animated.View>
  );
};

const styles = StyleSheet.create({
  badgeBackground: {
    position: 'absolute',
    width: '100%',
    height: '100%',
    borderRadius: 50,
    borderColor: 'transparent',
    borderWidth: 1,
    alignSelf: 'center',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  badgesContainer: {
    flexDirection: 'column',
    justifyContent: 'space-between',
    alignItems: 'center',
    width: 38,
    left: '5%',
    paddingBottom: '2%',
  },
  badgeButton: {
    width: 30,
    height: 30,
    borderRadius: 15,
  },
  animatedBadgeView: {position: 'absolute'},
  universityIconContainer: {
    width: normalize(31),
    height: normalize(38),
  },
});

export default BadgesDropdown;
