import {useNavigation} from '@react-navigation/native';
import React, {useEffect, useState} from 'react';
import {ScrollView, StyleSheet, Text, View} from 'react-native';
import {checkPermission, getAll} from 'react-native-contacts';
import {TouchableOpacity} from 'react-native-gesture-handler';
import {useDispatch, useSelector, useStore} from 'react-redux';
import {TAGG_LIGHT_BLUE} from '../../constants';
import {usersFromContactsService} from '../../services';
import {NO_USER} from '../../store/initialStates';
import {RootState} from '../../store/rootReducer';
import {ProfilePreviewType, ScreenType} from '../../types';
import {normalize, SCREEN_HEIGHT, SCREEN_WIDTH} from '../../utils';
import {handleAddFriend, handleUnfriend} from '../../utils/friends';
import {ProfilePreview} from '../profile';
import FindFriendsBlueIcon from '../../assets/icons/findFriends/find-friends-blue-icon.svg';

interface FriendsProps {
  result: Array<ProfilePreviewType>;
  screenType: ScreenType;
  userId: string;
}

const Friends: React.FC<FriendsProps> = ({result, screenType, userId}) => {
  const dispatch = useDispatch();
  const navigation = useNavigation();
  const {user: loggedInUser = NO_USER} = useSelector(
    (state: RootState) => state.user,
  );
  const state = useStore().getState();
  const [usersFromContacts, setUsersFromContacts] = useState<
    ProfilePreviewType[]
  >([]);

  const extractPhoneNumbers = async () => {
    let phoneNumbers: Array<string> = [];
    await getAll().then((contacts) => {
      contacts.map((contact) => {
        contact.phoneNumbers.map(async (phoneNumber) => {
          phoneNumbers.push(await phoneNumber.number);
        });
      });
    });
    return phoneNumbers;
  };

  useEffect(() => {
    const handleFindFriends = () => {
      extractPhoneNumbers().then(async (phoneNumbers) => {
        const permission = await checkPermission();
        if (permission === 'authorized') {
          let response = await usersFromContactsService(phoneNumbers);
          await setUsersFromContacts(response.existing_tagg_users);
          usersFromContacts.map((user) => console.log('user: ', user.username));
        } else if (permission === 'undefined') {
          navigation.navigate('RequestContactsAccess');
        } else {
          console.log('Go to settings');
        }
      });
    };
    handleFindFriends();
  }, []);

  const UsersFromContacts = () => (
    <>
      {usersFromContacts?.splice(0, 2).map((profilePreview) => (
        <View key={profilePreview.id} style={styles.container}>
          <View style={styles.friend}>
            <ProfilePreview
              {...{profilePreview}}
              previewType={'Friend'}
              screenType={screenType}
            />
          </View>
          <TouchableOpacity
            style={styles.button}
            onPress={() => {
              console.log('screentype: ', screenType);
              handleAddFriend(screenType, profilePreview, dispatch, state).then(
                (success) => {
                  if (success) {
                    let users = usersFromContacts;
                    setUsersFromContacts(
                      users.filter(
                        (user) => user.username !== profilePreview.username,
                      ),
                    );
                  }
                },
              );
            }}>
            <Text style={styles.buttonTitle}>Add Friend</Text>
          </TouchableOpacity>
        </View>
      ))}
    </>
  );

  return (
    <>
      <View style={styles.subheader}>
        <View style={styles.addFriendHeaderContainer}>
          <Text style={[styles.subheaderText]}>Add Friends</Text>
          <TouchableOpacity
            style={{flexDirection: 'row'}}
            onPress={() =>
              navigation.navigate('InviteFriendsScreen', {
                screenType: ScreenType.Profile,
              })
            }>
            <FindFriendsBlueIcon width={20} height={20} />
            <Text style={styles.findFriendsSubheaderText}>Find Friends</Text>
          </TouchableOpacity>
        </View>
        <UsersFromContacts />
      </View>
      <Text style={[styles.subheaderText, styles.friendsSubheaderText]}>
        Friends
      </Text>
      <ScrollView
        keyboardShouldPersistTaps={'always'}
        style={styles.scrollView}
        contentContainerStyle={styles.scrollViewContent}
        showsVerticalScrollIndicator={false}>
        {result.map((profilePreview) => (
          <View key={profilePreview.id} style={styles.container}>
            <View style={styles.friend}>
              <ProfilePreview
                {...{profilePreview}}
                previewType={'Friend'}
                screenType={screenType}
              />
            </View>
            {loggedInUser.userId !== userId && (
              <TouchableOpacity
                style={styles.button}
                onPress={() =>
                  handleUnfriend(screenType, profilePreview, dispatch, state)
                }>
                <Text style={styles.buttonTitle}>Unfriend</Text>
              </TouchableOpacity>
            )}
          </View>
        ))}
      </ScrollView>
    </>
  );
};

const styles = StyleSheet.create({
  scrollView: {
    flexDirection: 'column',
    alignSelf: 'center',
    width: SCREEN_WIDTH * 0.85,
  },
  firstScrollView: {},
  scrollViewContent: {
    alignSelf: 'center',
    paddingBottom: SCREEN_HEIGHT / 7,
    width: SCREEN_WIDTH * 0.85,
    marginTop: '1%',
  },
  addFriendHeaderContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: '3%',
    marginTop: '2%',
  },
  header: {flexDirection: 'row'},
  subheader: {
    alignSelf: 'center',
    width: SCREEN_WIDTH * 0.85,
    marginVertical: '1%',
  },
  subheaderText: {
    color: '#828282',
    fontSize: normalize(12),
    fontWeight: '600',
    lineHeight: normalize(14.32),
  },
  friendsSubheaderText: {
    alignSelf: 'center',
    width: SCREEN_WIDTH * 0.85,
    marginVertical: '1%',
    marginBottom: '2%',
  },
  findFriendsSubheaderText: {
    color: '#08E2E2',
    fontSize: normalize(12),
    fontWeight: '600',
    lineHeight: normalize(14.32),
  },
  container: {
    alignSelf: 'center',
    flexDirection: 'row',
    justifyContent: 'space-between',
    width: '100%',
    height: normalize(42),
    alignItems: 'center',
    marginBottom: '5%',
  },
  friend: {
    alignSelf: 'center',
    height: '100%',
  },
  addFriendButton: {
    alignSelf: 'center',
    justifyContent: 'center',
    alignItems: 'center',
    width: '100%',
    height: '55%',
    borderColor: TAGG_LIGHT_BLUE,
    borderWidth: 2,
    borderRadius: 2,
    padding: 0,
    backgroundColor: TAGG_LIGHT_BLUE,
  },
  addFriendButtonTitle: {
    color: 'white',
    padding: 0,
    fontSize: normalize(11),
    fontWeight: '700',
    lineHeight: normalize(13.13),
    letterSpacing: normalize(0.6),
    paddingHorizontal: '3.8%',
  },
  button: {
    alignSelf: 'center',
    justifyContent: 'center',
    alignItems: 'center',
    width: 82,
    height: '55%',
    borderColor: TAGG_LIGHT_BLUE,
    borderWidth: 2,
    borderRadius: 2,
    padding: 0,
    backgroundColor: TAGG_LIGHT_BLUE,
  },
  buttonTitle: {
    color: 'white',
    padding: 0,
    fontSize: normalize(11),
    fontWeight: '700',
    lineHeight: normalize(13.13),
    letterSpacing: normalize(0.6),
    paddingHorizontal: '3.8%',
  },
});

export default Friends;
