import {useNavigation} from '@react-navigation/native';
import React, {Fragment, 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 WhiteRing from '../../assets/icons/ring-white.svg';
import {
  INTEGRATED_SOCIAL_LIST,
  SOCIAL_ICON_SIZE_ADJUSTMENT,
  TAGG_RING_DIM,
} from '../../constants';
import {
  getNonIntegratedURL,
  handlePressForAuthBrowser,
  registerNonIntegratedSocialLink,
} from '../../services';
import {SmallSocialIcon, SocialIcon, SocialLinkModal} from '../common';
import {ScreenType, UserType} from '../../types';
import {
  ERROR_LINK,
  ERROR_UNABLE_TO_FIND_PROFILE,
  SUCCESS_LINK,
} from '../../constants/strings';
import {canViewProfile, normalize} from '../../utils';
import {RootState} from '../../store/rootReducer';
import {useStore} from 'react-redux';

interface TaggProps {
  social: string;
  isLinked: boolean;
  isIntegrated: boolean;
  setTaggsNeedUpdate: (_: boolean) => void;
  setSocialDataNeedUpdate: (social: string, username: string) => void;
  userXId: string | undefined;
  user: UserType;
  whiteRing: boolean | undefined;
  screenType: ScreenType;
}

const Tagg: React.FC<TaggProps> = ({
  social,
  isLinked,
  isIntegrated,
  setTaggsNeedUpdate,
  setSocialDataNeedUpdate,
  userXId,
  screenType,
  user,
  whiteRing,
}) => {
  const navigation = useNavigation();
  const state: RootState = useStore().getState();
  const [modalVisible, setModalVisible] = useState(false);
  const youMayPass = isLinked || userXId;

  /*
  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 (canViewProfile(state, userXId, screenType)) {
        if (INTEGRATED_SOCIAL_LIST.indexOf(social) !== -1) {
          navigation.navigate('SocialMediaTaggs', {
            socialMediaType: social,
            userXId,
          });
        } else {
          getNonIntegratedURL(social, user.userId).then((socialURL) => {
            if (socialURL) {
              Linking.openURL(socialURL);
            } else {
              Alert.alert(ERROR_UNABLE_TO_FIND_PROFILE);
            }
          });
        }
      }
    } else {
      if (isIntegrated) {
        handlePressForAuthBrowser(social).then((success) => {
          setTaggsNeedUpdate(success);
          if (success) {
            setSocialDataNeedUpdate(social, '');
          }
        });
      } else {
        setModalVisible(true);
      }
    }
  };

  const pickTheRightRingHere = () => {
    if (whiteRing && !userXId) {
      return <WhiteRing width={TAGG_RING_DIM} height={TAGG_RING_DIM} />;
    }
    if (youMayPass) {
      if (whiteRing) {
        return <WhiteRing width={TAGG_RING_DIM} height={TAGG_RING_DIM} />;
      }
      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(SUCCESS_LINK(social));
      setTaggsNeedUpdate(true);
      setSocialDataNeedUpdate(social, username);
    } else {
      // If we display too fast the alert will get dismissed with the modal
      setTimeout(() => {
        Alert.alert(ERROR_LINK(social));
      }, 500);
    }
  };

  return (
    <>
      {userXId && !isLinked ? (
        <Fragment />
      ) : (
        <>
          <SocialLinkModal
            social={social}
            modalVisible={modalVisible}
            setModalVisible={setModalVisible}
            completionCallback={linkNonIntegratedSocial}
          />
          <View style={whiteRing ? styles.spcontainer : styles.container}>
            <TouchableOpacity
              style={styles.iconTap}
              onPress={modalOrAuthBrowserOrPass}>
              <SocialIcon style={styles.icon} social={social} whiteRing />
              {pickTheRightRingHere()}
            </TouchableOpacity>
            {!whiteRing && (
              <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({
  spcontainer: {
    justifyContent: 'space-between',
    alignItems: 'center',
    marginRight: 15,
    marginLeft: 19,
    height: normalize(60),
  },
  container: {
    justifyContent: 'space-between',
    alignItems: 'center',
    marginRight: 15,
    marginLeft: 15,
    height: normalize(90),
  },
  iconTap: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  icon: {
    width: '77%',
    height: '77%',
    borderRadius: 30,
    position: 'absolute',
  },
  smallIconContainer: {
    height: 20,
    width: 20,
    position: 'absolute',
    justifyContent: 'center',
    alignItems: 'center',
    bottom: 0,
  },
  smallIcon: {
    borderRadius: 1000,
  },
});

export default Tagg;
