import {useNavigation} from '@react-navigation/core';
import React, {useEffect, useState} from 'react';
import {
  ActivityIndicator,
  FlatList,
  Image,
  Modal,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import {TouchableOpacity} from 'react-native-gesture-handler';
import LinearGradient from 'react-native-linear-gradient';
import {useSelector} from 'react-redux';
import CloseIcon from '../../assets/ionicons/close-outline.svg';
import {BADGE_GRADIENT_FIRST} from '../../constants';
import {BADGE_DATA} from '../../constants/badges';
import {getSuggestedPeopleProfile, removeBadgesService} from '../../services';
import {RootState} from '../../store/rootreducer';
import {UniversityBadge, UniversityType} from '../../types';
import {getUniversityBadge, normalize} from '../../utils';

interface BadgeDetailModalProps {
  isEditable: boolean;
  setBadgeViewVisible: Function;
  name?: string;
}

const BadgeDetailView: React.FC<BadgeDetailModalProps> = ({
  name,
  isEditable = true,
  setBadgeViewVisible,
}) => {
  const {
    user: {userId = ''},
  } = useSelector((state: RootState) => state.user);
  const navigation = useNavigation();
  const [selectedBadges, setSelectedBadges] = useState<UniversityBadge[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedBadgesWithImage, setSelectedBadgesWithImage] = useState<any[]>(
    [],
  );

  const fetchBadges = async () => {
    if (userId) {
      const response = await getSuggestedPeopleProfile(userId);
      if (response) {
        const data = response.badges;
        let extractedBadgeNames: UniversityBadge[] = [];
        data.forEach((badge) => {
          extractedBadgeNames.push(badge);
        });
        setSelectedBadges(extractedBadgeNames);
      }
    }
  };

  useEffect(() => {
    setIsLoading(true);
    fetchBadges();
  }, []);

  useEffect(() => {
    let badgesWithImage = [];
    selectedBadges.forEach((e) => {
      const uniData = BADGE_DATA[e.university];
      const categoryData = uniData.filter((u) => {
        return u.title === e.category;
      });
      const badgeData = categoryData[0].data.filter((c) => {
        return c.badgeName === e.name;
      });
      badgeData.forEach((c) => {
        const obj = {...e, badgeImage: c.badgeImage};
        badgesWithImage.push(obj);
      });
    });
    setTimeout(() => {
      setSelectedBadgesWithImage(badgesWithImage);
      setIsLoading(false);
    }, 500);
  }, [selectedBadges]);

  const removeBadgeCell = async (badge: string) => {
    setIsLoading(true);
    await removeBadgesService([badge], userId);
    fetchBadges();
  };

  const badgeEditCell = ({item: {id, name, badgeImage}}) => {
    return (
      <TouchableOpacity
        style={styles.badgeCellContainerStyles}
        onPress={() => {
          setBadgeViewVisible(false);
          navigation.navigate('MutualBadgeHolders', {
            badge_id: id,
            badge_title: name,
            badge_img: badgeImage,
          });
        }}>
        <View
          style={
            isEditable
              ? styles.badgeCellImageContainerStyles
              : styles.badgeCellImageNoEditContainerStyles
          }>
          <LinearGradient
            colors={BADGE_GRADIENT_FIRST}
            useAngle={true}
            style={styles.badgeCellImageStyles}
            angle={136.69}>
            <Image
              resizeMode="cover"
              style={styles.badgeImageStyles}
              source={badgeImage}
            />
          </LinearGradient>
          {isEditable && (
            <TouchableOpacity
              onPress={() => {
                removeBadgeCell(name);
              }}>
              <CloseIcon height={25} width={25} color="gray" />
            </TouchableOpacity>
          )}
        </View>
        <View style={styles.userNameContainerStyles}>
          <Text style={styles.badgeCellTextStyles}>{name}</Text>
        </View>
      </TouchableOpacity>
    );
  };

  const addButton = () => {
    return (
      <TouchableOpacity
        onPress={() => {
          setBadgeViewVisible(false);
          navigation.navigate('BadgeSelection', {editing: true});
        }}
        style={styles.addButtonStyles}>
        <Text style={styles.addButtonTextStyles}>Add Badges</Text>
      </TouchableOpacity>
    );
  };

  const modalHeader = () => {
    const heading = isEditable ? 'Edit your badges!' : name;
    const subheading = isEditable
      ? 'Add or delete your badges'
      : 'View badges to discover groups!';
    return (
      <View>
        <Text style={styles.modalHeadingStyles}>{heading}</Text>
        <Text style={styles.modalSubheadingStyles}>{subheading}</Text>
      </View>
    );
  };

  const _modalContent = () => {
    return (
      <View style={styles.viewWrapper}>
        <View style={styles.modalView}>
          <View style={styles.modalUpperContainerStyles}>
            <TouchableOpacity
              style={styles.crossButtonStyles}
              onPress={() => setBadgeViewVisible(false)}>
              <CloseIcon height={25} width={25} color="gray" />
            </TouchableOpacity>
            <View style={styles.modalImageContainerStyles}>
              <Image
                style={styles.modalImageStyles}
                source={getUniversityBadge(UniversityType.Brown, 'Crest')}
              />
            </View>
          </View>
          {modalHeader()}
          {!isLoading && (
            <View>
              <FlatList
                contentContainerStyle={styles.modalListStyles}
                scrollEnabled={false}
                data={selectedBadgesWithImage}
                numColumns={3}
                renderItem={badgeEditCell}
                keyExtractor={(item) => item.id.toString()}
              />
            </View>
          )}
          {isLoading && _loaderView()}
          {isEditable && addButton()}
        </View>
      </View>
    );
  };

  const _loaderView = () => {
    return (
      <View style={styles.loaderStyles}>
        <ActivityIndicator animating={isLoading} size="large" color="black" />
      </View>
    );
  };

  return (
    <Modal
      animationType="slide"
      transparent
      visible={true}
      presentationStyle="overFullScreen">
      {_modalContent()}
    </Modal>
  );
};

const styles = StyleSheet.create({
  badgeCellContainerStyles: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 10,
  },
  badgeCellImageContainerStyles: {
    flexDirection: 'row',
    marginLeft: 25,
  },
  badgeImageStyles: {
    width: '50%',
    height: '50%',
    alignSelf: 'center',
  },
  badgeCellImageNoEditContainerStyles: {
    flexDirection: 'row',
    marginHorizontal: 25,
  },
  badgeCellImageStyles: {
    borderRadius: 50,
    width: 70,
    height: 70,
    justifyContent: 'center',
  },
  badgeCellTextStyles: {
    fontWeight: '600',
    fontSize: normalize(12),
    lineHeight: normalize(16),
    textAlign: 'center',
  },
  userNameContainerStyles: {marginTop: 10},
  crossButtonStyles: {marginTop: 10, marginLeft: 10},
  addButtonStyles: {
    height: 40,
    borderRadius: 5,
    marginBottom: 45,
    width: '40%',
    marginTop: 14,
    alignItems: 'center',
    justifyContent: 'center',
    alignSelf: 'center',
    backgroundColor: '#698DD3',
  },
  addButtonTextStyles: {color: 'white'},
  modalHeadingStyles: {
    fontWeight: '600',
    fontSize: normalize(17),
    lineHeight: normalize(20.29),
    textAlign: 'center',
  },
  loaderStyles: {justifyContent: 'center', marginVertical: 20},
  modalSubheadingStyles: {
    fontWeight: '600',
    fontSize: normalize(11),
    lineHeight: normalize(15),
    textAlign: 'center',
    color: '#828282',
  },
  modalUpperContainerStyles: {
    flexDirection: 'row',
    alignItems: 'flex-start',
  },
  modalImageContainerStyles: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  modalImageStyles: {left: -15, top: -30},
  modalListStyles: {
    alignSelf: 'center',
    marginVertical: 35,
  },
  viewWrapper: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.2)',
  },
  modalView: {
    width: '95%',
    backgroundColor: '#fff',
    borderRadius: 7,
  },
});

export default BadgeDetailView;
