import {useNavigation} from '@react-navigation/native';
import React, {Fragment, useContext, useEffect, useState} from 'react';
import {Alert, Linking, StyleSheet, TouchableOpacity, View} from 'react-native';
import PurpleRingPlus from '../../assets/icons/purple_ring+.svg';
import PurpleRing from '../../assets/icons/purple_ring.svg';
import RingPlus from '../../assets/icons/ring+.svg';
import Ring from '../../assets/icons/ring.svg';
import {
  INTEGRATED_SOCIAL_LIST,
  SOCIAL_ICON_SIZE_ADJUSTMENT,
  TAGG_ICON_DIM,
  TAGG_RING_DIM,
} from '../../constants';
import {
  getNonIntegratedURL,
  handlePressForAuthBrowser,
  registerNonIntegratedSocialLink,
} from '../../services';
import {SmallSocialIcon, SocialIcon, SocialLinkModal} from '../common';
import {useSelector} from 'react-redux';
import {RootState} from '../../store/rootreducer';
import {ScreenType} from '../../types';

interface TaggProps {
  social: string;
  isLinked: boolean;
  isIntegrated: boolean;
  setTaggsNeedUpdate: (_: boolean) => void;
  setSocialDataNeedUpdate: (_: string) => void;
  userXId: string;
  screenType: ScreenType;
}

const Tagg: React.FC<TaggProps> = ({
  social,
  isLinked,
  isIntegrated,
  setTaggsNeedUpdate,
  setSocialDataNeedUpdate,
  userXId,
  screenType,
}) => {
  const navigation = useNavigation();
  const [modalVisible, setModalVisible] = useState(false);
  const youMayPass = isLinked || userXId;
  const {user} = userXId
    ? useSelector((state: RootState) => state.userX[screenType][userXId])
    : useSelector((state: RootState) => state.user);
  /*
  case isProfileView:
    case linked:
      show normal ring, navigate to taggs view
    case !linked:
      don't show tagg
  case !isProfileView:
    case linked:
      show normal ring, navigate to taggs view
    case !linked:
      show ring+, then...
        case integrated_social:
          show auth browser
        case !integrated_social:
          show modal
  Tagg's "Tagg" will use the Ring instead of PurpleRing 
  */

  const modalOrAuthBrowserOrPass = async () => {
    if (youMayPass) {
      if (INTEGRATED_SOCIAL_LIST.indexOf(social) !== -1) {
        navigation.push('SocialMediaTaggs', {
          socialMediaType: social,
          userXId,
        });
      } else {
        getNonIntegratedURL(social, user.userId).then((socialURL) => {
          if (socialURL) {
            Linking.openURL(socialURL);
          } else {
            Alert.alert('We were unable to find this profile 😔');
          }
        });
      }
    } else {
      if (isIntegrated) {
        handlePressForAuthBrowser(social).then((success) => {
          setTaggsNeedUpdate(success);
          if (success) setSocialDataNeedUpdate(social);
        });
      } else {
        setModalVisible(true);
      }
    }
  };

  const pickTheRightRingHere = () => {
    if (youMayPass) {
      if (social === 'Tagg') {
        return <Ring width={TAGG_RING_DIM} height={TAGG_RING_DIM} />;
      } else {
        return <PurpleRing width={TAGG_RING_DIM} height={TAGG_RING_DIM} />;
      }
    } else {
      if (social === 'Tagg') {
        return <RingPlus width={TAGG_RING_DIM} height={TAGG_RING_DIM} />;
      } else {
        return <PurpleRingPlus width={TAGG_RING_DIM} height={TAGG_RING_DIM} />;
      }
    }
  };

  const linkNonIntegratedSocial = async (username: string) => {
    if (await registerNonIntegratedSocialLink(social, username)) {
      Alert.alert(`Successfully linked ${social} 🎉`);
      setTaggsNeedUpdate(true);
    } else {
      // If we display too fast the alert will get dismissed with the modal
      setTimeout(() => {
        Alert.alert(`Something went wrong, we can't link with ${social} 😔`);
      }, 500);
    }
  };

  return (
    <>
      {userXId && !isLinked ? (
        <Fragment />
      ) : (
        <>
          <SocialLinkModal
            modalVisible={modalVisible}
            setModalVisible={setModalVisible}
            completionCallback={linkNonIntegratedSocial}
          />
          <View style={styles.container}>
            <TouchableOpacity
              style={styles.iconTap}
              onPress={modalOrAuthBrowserOrPass}>
              <SocialIcon style={styles.icon} social={social} />
              {pickTheRightRingHere()}
            </TouchableOpacity>
            <View style={styles.smallIconContainer}>
              <SmallSocialIcon
                style={[
                  styles.smallIcon,
                  {
                    height: SOCIAL_ICON_SIZE_ADJUSTMENT[social],
                    width: SOCIAL_ICON_SIZE_ADJUSTMENT[social],
                  },
                ]}
                social={social}
              />
            </View>
          </View>
        </>
      )}
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    alignItems: 'center',
    marginHorizontal: 15,
  },
  iconTap: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  icon: {
    width: TAGG_ICON_DIM,
    height: TAGG_ICON_DIM,
    borderRadius: TAGG_ICON_DIM / 2,
    position: 'absolute',
  },
  smallIconContainer: {
    height: 35,
    width: 35,
    position: 'absolute',
    justifyContent: 'center',
    alignItems: 'center',
    bottom: -35,
  },
  smallIcon: {
    borderRadius: 1000,
  },
});

export default Tagg;
