import {useNavigation} from '@react-navigation/core';
import React, {useEffect, useState} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {ScrollView, TouchableOpacity} from 'react-native-gesture-handler';
import {useSelector} from 'react-redux';
import {BadgeIcon} from '..';
import PlusIcon from '../../assets/icons/plus_icon-01.svg';
import {BADGE_LIMIT} from '../../constants';
import {RootState} from '../../store/rootReducer';
import {ScreenType, UniversityBadgeDisplayType} from '../../types';
import {badgesToDisplayBadges, normalize} from '../../utils';
import BadgeDetailView from '../common/BadgeDetailView';

interface ProfileBadgesProps {
  userXId: string | undefined;
  screenType: ScreenType;
}

const ProfileBadges: React.FC<ProfileBadgesProps> = ({userXId, screenType}) => {
  const navigation = useNavigation();
  const {badges, name} = useSelector((state: RootState) =>
    userXId ? state.userX[screenType][userXId].profile : state.user.profile,
  );
  const [displayBadges, setDisplayBadges] = useState<
    UniversityBadgeDisplayType[]
  >([]);
  const [isEditBadgeModalVisible, setIsEditBadgeModalVisible] = useState(false);
  const isOwnProfile = userXId === undefined;

  useEffect(() => {
    setDisplayBadges(badgesToDisplayBadges(badges));
  }, [badges]);

  return (
    <>
      {/* Tutorial text */}
      {displayBadges.length === 0 && isOwnProfile && (
        <>
          <Text style={styles.title}>Badges</Text>
          <Text style={styles.body}>
            Proudly represent your team, club, or organization!
          </Text>
        </>
      )}
      {displayBadges.length === 0 && isOwnProfile && (
        // Grey circle placeholders
        <ScrollView
          contentContainerStyle={styles.badgeContainer}
          scrollEnabled={false}
          horizontal>
          <TouchableOpacity
            onPress={() =>
              navigation.navigate('BadgeSelection', {editing: true})
            }>
            <PlusIcon
              width={normalize(31)}
              height={normalize(31)}
              color={'black'}
              style={{transform: [{scale: 1.2}]}}
            />
          </TouchableOpacity>
          {Array(BADGE_LIMIT)
            .fill(0)
            .map(() => (
              <View style={[styles.grey, styles.circle]} />
            ))}
        </ScrollView>
      )}
      {displayBadges.length !== 0 && (
        // Populating actual badges
        <ScrollView
          contentContainerStyle={styles.badgeContainer}
          scrollEnabled={false}
          horizontal>
          {/* Actual badges */}
          {displayBadges.map((displayBadge) => (
            <BadgeIcon key={displayBadge.id} badge={displayBadge} />
          ))}
          {/* Plus icon */}
          {displayBadges.length < BADGE_LIMIT && isOwnProfile && (
            <TouchableOpacity
              onPress={() =>
                navigation.navigate('BadgeSelection', {editing: true})
              }>
              <PlusIcon
                width={normalize(31)}
                height={normalize(31)}
                color={'black'}
                style={{transform: [{scale: 1.2}]}}
              />
            </TouchableOpacity>
          )}
          {/* Empty placeholders for space-between styling */}
          {Array(BADGE_LIMIT + 1)
            .fill(0)
            .splice(displayBadges.length + 1, BADGE_LIMIT)
            .map(() => (
              <View style={styles.circle} />
            ))}
          {/* X button */}
          {displayBadges.length === BADGE_LIMIT && isOwnProfile && (
            <TouchableOpacity onPress={() => setIsEditBadgeModalVisible(true)}>
              <PlusIcon
                width={normalize(31)}
                height={normalize(31)}
                color={'grey'}
                style={{transform: [{scale: 1.2}, {rotate: '45deg'}]}}
              />
            </TouchableOpacity>
          )}
        </ScrollView>
      )}
      {isEditBadgeModalVisible && (
        <BadgeDetailView
          userXId={userXId}
          screenType={screenType}
          isEditable={isOwnProfile}
          userFullName={name}
          setBadgeViewVisible={setIsEditBadgeModalVisible}
        />
      )}
    </>
  );
};

const styles = StyleSheet.create({
  title: {
    fontWeight: '600',
    fontSize: normalize(13.5),
    lineHeight: normalize(18),
  },
  body: {
    fontSize: normalize(13.5),
    lineHeight: normalize(17),
    marginBottom: 10,
  },
  badgeContainer: {
    width: '100%',
    justifyContent: 'space-between',
    marginTop: 10,
    marginBottom: 15,
  },
  circle: {
    width: normalize(31),
    height: normalize(31),
    borderRadius: normalize(31) / 2,
  },
  grey: {
    backgroundColor: '#c4c4c4',
  },
});

export default ProfileBadges;
