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

interface BadgeDetailModalProps {
  isEditable: boolean;
  setBadgeViewVisible: Function;
  selectedBadges: UniversityBadge[];
  name?: string;
  userId: string;
}

const BadgeDetailView: React.FC<BadgeDetailModalProps> = ({
  name,
  isEditable = true,
  setBadgeViewVisible,
  selectedBadges,
}) => {
  const navigation = useNavigation();
  const [removableBadges, setRemovableBadges] = useState([]);

  const {
    user: {userId = ''},
  } = useSelector((state: RootState) => state.user);

  const removeBadgeCell = async () => {
    await removeBadgesService(removableBadges, userId);
  };

  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={{
                width: 70,
                height: 70,
                alignSelf: 'center',
              }}
              source={badgeImage}
            />
          </LinearGradient>
          {isEditable && (
            <TouchableOpacity
              onPress={() => {
                selectedBadges = selectedBadges.filter((b) => b.id === id);
                const obj = {id, name};
                removableBadges.push(obj);
                removeBadgeCell();
              }}>
              <CloseIcon height={25} width={25} color="gray" />
            </TouchableOpacity>
          )}
        </View>
        <View style={{marginTop: 10}}>
          <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>
    );
  };

  return (
    <Modal
      animationType="slide"
      transparent
      visible={true}
      presentationStyle="overFullScreen">
      <View style={styles.viewWrapper}>
        <View style={styles.modalView}>
          <View style={styles.modalUpperContainerStyles}>
            <TouchableOpacity
              style={{marginTop: 10, marginLeft: 10}}
              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()}
          <View>
            <FlatList
              contentContainerStyle={styles.modalListStyles}
              scrollEnabled={false}
              data={selectedBadges}
              numColumns={3}
              renderItem={badgeEditCell}
              keyExtractor={(item) => item.id.toString()}
            />
          </View>
          {isEditable && addButton()}
        </View>
      </View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  badgeCellContainerStyles: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: 10,
  },
  badgeCellImageContainerStyles: {
    flexDirection: 'row',
    marginLeft: 25,
  },
  badgeCellImageNoEditContainerStyles: {
    flexDirection: 'row',
    marginHorizontal: 25,
  },
  badgeCellImageStyles: {
    borderRadius: 50,
  },
  badgeCellTextStyles: {
    fontWeight: '600',
    fontSize: normalize(12),
    lineHeight: normalize(16),
    textAlign: 'center',
  },
  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',
  },
  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;
