import React, {useContext} from 'react';
import {
  Alert,
  LayoutChangeEvent,
  Linking,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import {normalize} from 'react-native-elements';
import {useDispatch, useSelector, useStore} from 'react-redux';
import {TAGG_DARK_BLUE, TOGGLE_BUTTON_TYPE} from '../../constants';
import {
  acceptFriendRequest,
  declineFriendRequest,
  updateUserXFriends,
  updateUserXProfileAllScreens,
} from '../../store/actions';
import {canViewProfile} from '../../utils/users';
import {NO_PROFILE} from '../../store/initialStates';
import {RootState} from '../../store/rootReducer';
import {ScreenType} from '../../types';
import {
  connectChatAccount,
  getUserAsProfilePreviewType,
  SCREEN_HEIGHT,
  SCREEN_WIDTH,
} from '../../utils';
import {FriendsButton, BasicButton} from '../common';
import ToggleButton from './ToggleButton';
import {ChatContext} from '../../App';
import {useNavigation} from '@react-navigation/core';

interface ProfileBodyProps {
  onLayout: (event: LayoutChangeEvent) => void;
  isBlocked: boolean;
  handleBlockUnblock: () => void;
  userXId: string | undefined;
  screenType: ScreenType;
}
const ProfileBody: React.FC<ProfileBodyProps> = ({
  onLayout,
  isBlocked,
  handleBlockUnblock,
  userXId,
  screenType,
}) => {
  const dispatch = useDispatch();
  const navigation = useNavigation();

  const {profile = NO_PROFILE, user} = useSelector((state: RootState) =>
    userXId ? state.userX[screenType][userXId] : state.user,
  );

  const {
    biography,
    website,
    friendship_status,
    friendship_requester_id,
  } = profile;

  const {id, username, first_name, last_name} = getUserAsProfilePreviewType(
    user,
    profile,
  );

  const {chatClient, setChannel} = useContext(ChatContext);

  const state: RootState = useStore().getState();
  const loggedInUserId = state.user.user.userId;

  const handleAcceptRequest = async () => {
    await dispatch(acceptFriendRequest({id, username, first_name, last_name}));
    await dispatch(updateUserXFriends(id, state));
    dispatch(updateUserXProfileAllScreens(id, state));
  };

  const handleDeclineFriendRequest = async () => {
    await dispatch(declineFriendRequest(id));
    dispatch(updateUserXProfileAllScreens(id, state));
  };

  const canMessage = () => {
    if (
      userXId &&
      !isBlocked &&
      (friendship_status === 'no_record' ||
        friendship_status === 'friends' ||
        (friendship_status === 'requested' &&
          friendship_requester_id === loggedInUserId)) &&
      canViewProfile(state, userXId, screenType)
    ) {
      return true;
    } else {
      return false;
    }
  };

  const onPressMessage = async () => {
    let connected: boolean = !chatClient.user;
    if (!connected) {
      connected = await connectChatAccount(loggedInUserId, chatClient);
      if (!connected) {
        Alert.alert('Unable to connect chat');
      }
    } else {
      const channel = chatClient.channel('messaging', {
        members: [loggedInUserId, String(userXId)],
      });
      channel.create();
      setChannel(channel);
      navigation.navigate('Chat');
    }
  };

  return (
    <View onLayout={onLayout} style={styles.container}>
      <Text style={styles.username}>{`@${username}`}</Text>
      {biography.length > 0 && (
        <Text style={styles.biography}>{`${biography}`}</Text>
      )}
      {website.length > 0 && (
        <Text
          style={styles.website}
          onPress={() => {
            Linking.openURL(
              website.startsWith('http') ? website : 'http://' + website,
            );
          }}>{`${website}`}</Text>
      )}

      {userXId && isBlocked && (
        <View style={styles.toggleButtonContainer}>
          <ToggleButton
            toggleState={isBlocked}
            handleToggle={handleBlockUnblock}
            buttonType={TOGGLE_BUTTON_TYPE.BLOCK_UNBLOCK}
          />
        </View>
      )}
      <View style={styles.simpleRowContainer}>
        {userXId && !isBlocked && (
          <View style={styles.buttonsContainer}>
            <FriendsButton
              userXId={userXId}
              screenType={screenType}
              friendship_requester_id={friendship_requester_id}
              onAcceptRequest={handleAcceptRequest}
              onRejectRequest={handleDeclineFriendRequest}
            />
            {canMessage() && (
              <BasicButton
                title={'Message'}
                onPress={onPressMessage}
                externalStyles={{
                  container: {
                    width: SCREEN_WIDTH * 0.42,
                    aspectRatio: 154 / 33,
                  },
                }}
              />
            )}
          </View>
        )}
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  toggleButtonContainer: {
    flexDirection: 'row',
    flex: 1,
    paddingTop: '3.5%',
    paddingBottom: '2%',
  },
  simpleRowContainer: {flexDirection: 'row'},
  buttonsContainer: {
    flex: 1,
    paddingTop: '3.5%',
    paddingBottom: '2%',
    width: '50%',
    height: SCREEN_HEIGHT * 0.1,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  container: {
    paddingVertical: '1%',
    paddingHorizontal: 18,
    backgroundColor: 'white',
  },
  username: {
    fontWeight: '600',
    fontSize: normalize(12),
    marginBottom: '1%',
  },
  biography: {
    fontSize: normalize(12),
    marginBottom: '1.5%',
  },
  website: {
    fontSize: normalize(12),
    color: TAGG_DARK_BLUE,
    marginBottom: '1%',
  },
});

export default ProfileBody;
