import AsyncStorage from '@react-native-community/async-storage';
import {StackNavigationProp} from '@react-navigation/stack';
import React, {useEffect, useState} from 'react';
import {Alert, SafeAreaView, StatusBar, StyleSheet, View} from 'react-native';
import {Text} from 'react-native-animatable';
import {TouchableOpacity} from 'react-native-gesture-handler';
import LinearGradient from 'react-native-linear-gradient';
import {useDispatch} from 'react-redux';
import {ADD_USER_BADGES, BACKGROUND_GRADIENT_MAP} from '../../constants';
import {
  ERROR_BADGES_EXCEED_LIMIT,
  ERROR_UPLOAD_BADGES,
} from '../../constants/strings';
import {suggestedPeopleBadgesFinished} from '../../store/actions';
import {BackgroundGradientType} from '../../types';
import {SCREEN_HEIGHT, StatusBarHeight} from '../../utils';
import BadgeList from './BadgeList';
import BadgeScreenHeader from './BadgeScreenHeader';

/**
 * Home Screen for displaying Tagg Badge Selections
 **/

export const BadgeImages = {
  football: require('../../assets/images/badges/football.png'),
  track: require('../../assets/images/badges/track.png'),
  volleyball: require('../../assets/images/badges/volleyball.png'),
  lax: require('../../assets/images/badges/brown_badge.png'),
  fieldHockey: require('../../assets/images/badges/field_hockey.png'),
  gymnastics: require('../../assets/images/badges/gymnastics.png'),
  hockey: require('../../assets/images/badges/hockey.png'),
  baseball: require('../../assets/images/badges/baseball.png'),
  basketball: require('../../assets/images/badges/basketball.png'),
  kappadelta: require('../../assets/images/badges/kappa_delta.png'),
  alphachiomega: require('../../assets/images/badges/alpha_chi_omega.png'),
  deltagamma: require('../../assets/images/badges/delta_gamma.png'),
  sigma: require('../../assets/images/badges/sigma.png'),
  thetaalpha: require('../../assets/images/badges/theta_alpha.png'),
  deltaphi: require('../../assets/images/badges/delta_phi.png'),
  kappaalphapsi: require('../../assets/images/badges/kappa_alpha_psi.png'),
  alphaphialpha: require('../../assets/images/badges/alpha_phi_alpha.png'),
  betaomegachi: require('../../assets/images/badges/beta_omega_chi.png'),
};

export const DATA = [
  {
    title: 'Athletics',
    data: [
      {
        badgeName: 'Brown Football',
        badgeImage: BadgeImages.football,
      },
      {
        badgeName: 'Brown Track',
        badgeImage: BadgeImages.track,
      },
      {
        badgeName: 'Brown Volleyball',
        badgeImage: BadgeImages.volleyball,
      },
      {
        badgeName: 'Brown LAX',
        badgeImage: BadgeImages.lax,
      },
      {
        badgeName: 'Brown Field Hockey',
        badgeImage: BadgeImages.fieldHockey,
      },
      {
        badgeName: 'Brown Gymnastics',
        badgeImage: BadgeImages.gymnastics,
      },
      {
        badgeName: 'Brown Hockey',
        badgeImage: BadgeImages.hockey,
      },
      {
        badgeName: 'Brown Baseball',
        badgeImage: BadgeImages.baseball,
      },
      {
        badgeName: 'Brown Basketball',
        badgeImage: BadgeImages.basketball,
      },
    ],
  },

  {
    title: 'Sorority',
    data: [
      {
        badgeName: 'Kappa Delta',
        badgeImage: BadgeImages.kappadelta,
      },
      {
        badgeName: 'Alpha Chi Omega',
        badgeImage: BadgeImages.alphachiomega,
      },
      {
        badgeName: 'Delta Gamma',
        badgeImage: BadgeImages.deltagamma,
      },
    ],
  },

  {
    title: 'Fraternity',
    data: [
      {
        badgeName: 'Sigma',
        badgeImage: BadgeImages.sigma,
      },
      {
        badgeName: 'Theta Alpha',
        badgeImage: BadgeImages.thetaalpha,
      },
      {
        badgeName: 'Delta Phi',
        badgeImage: BadgeImages.deltaphi,
      },
    ],
  },
  {
    title: 'Historically Black Fraternities',
    data: [
      {
        badgeName: 'Kappa Alpha Psi',
        badgeImage: BadgeImages.kappadelta,
      },
      {
        badgeName: 'Alpha Phi Alpha',
        badgeImage: BadgeImages.alphaphialpha,
      },
      {
        badgeName: 'Beta Omega Chi',
        badgeImage: BadgeImages.betaomegachi,
      },
    ],
  },
];

type BadgeSelectionParamList = {
  BadgeList: any[];
};

type BadgeSelectionScreenNavigationProp = StackNavigationProp<
  BadgeSelectionParamList,
  'BadgeList'
>;

type BadgeSelectionProps = {
  navigation: BadgeSelectionScreenNavigationProp;
};

const BadgeSelection: React.FC<BadgeSelectionProps> = ({navigation}) => {
  const [canSubmit, setCanSubmit] = useState(false);
  navigation.setOptions({
    headerRight: () => (
      <TouchableOpacity
        style={styles.rightButtonContainer}
        onPress={() => {
          if (canSubmit) {
            uploadUserSelection();
          }
        }}>
        <Text style={styles.rightButton}>{canSubmit ? 'Done' : 'Skip'}</Text>
      </TouchableOpacity>
    ),
  });

  const [selectedBadges, setSelectedBadges] = useState<string[]>([]);
  const selectKey = (key: string) => {
    if (selectedBadges.includes(key)) {
      const selectedBadgesArray = [...selectedBadges];
      const itemIndex = selectedBadgesArray.indexOf(key);
      if (itemIndex > -1) {
        selectedBadgesArray.splice(itemIndex, 1);
      }
      setSelectedBadges(selectedBadgesArray);
    } else {
      const selectedBadgesArray = [...selectedBadges, key];
      setSelectedBadges(selectedBadgesArray);
    }
  };
  const dispatch = useDispatch();
  useEffect(() => {
    setCanSubmit(selectedBadges.length !== 0);
  }, [selectedBadges]);

  const uploadUserSelection = async () => {
    try {
      const token = await AsyncStorage.getItem('token');
      const form = new FormData();
      form.append('badges', JSON.stringify(selectedBadges));
      const response = await fetch(ADD_USER_BADGES, {
        method: 'POST',
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: 'Token ' + token,
        },
        body: form,
      });
      if (response.status === 400) {
        Alert.alert(ERROR_BADGES_EXCEED_LIMIT);
        return;
      }
      dispatch(suggestedPeopleBadgesFinished());
    } catch (error) {
      console.log(error);
      Alert.alert(ERROR_UPLOAD_BADGES);
    }
  };

  return (
    <LinearGradient
      colors={BACKGROUND_GRADIENT_MAP[BackgroundGradientType.Dark]}
      style={styles.container}>
      <StatusBar barStyle={'light-content'} />
      <SafeAreaView>
        <View style={styles.listContainer}>
          <BadgeScreenHeader />
          {/* filter not working, comment out for now */}
          {/* <SearchBar
            style={styles.searchBarStyle}
            onCancel={() => {}}
            top={Animated.useValue(0)}
          /> */}
          <BadgeList
            data={DATA}
            selectedBadges={selectedBadges}
            selectKey={selectKey}
          />
        </View>
      </SafeAreaView>
    </LinearGradient>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  searchBarStyle: {
    width: '95%',
    alignSelf: 'center',
    marginTop: SCREEN_HEIGHT * 0.05,
  },
  viewContainer: {marginTop: StatusBarHeight},
  listContainer: {marginTop: SCREEN_HEIGHT * 0.05},
  rightButtonContainer: {marginRight: 24},
  rightButton: {
    color: '#FFFFFF',
    fontWeight: 'bold',
    fontSize: 15,
    lineHeight: 18,
  },
  leftButtonContainer: {marginLeft: 24},
  leftButton: {
    color: '#FFFFFF',
    fontWeight: '500',
    fontSize: 15,
    lineHeight: 18,
  },
});

export default BadgeSelection;
