import React from 'react';
import {StyleSheet, View, Text, LayoutChangeEvent, Linking} from 'react-native';
import {Button, normalize} from 'react-native-elements';
import {
  TAGG_DARK_BLUE,
  TAGG_LIGHT_BLUE,
  TOGGLE_BUTTON_TYPE,
} from '../../constants';
import ToggleButton from './ToggleButton';
import {RootState} from '../../store/rootReducer';
import {useDispatch, useSelector, useStore} from 'react-redux';
import {ScreenType} from '../../types';
import {NO_PROFILE, NO_USER} from '../../store/initialStates';
import {
  getUserAsProfilePreviewType,
  handleFriendUnfriend,
  SCREEN_WIDTH,
} from '../../utils';
import {AcceptDeclineButtons, FriendsButton} from '../common';
import {
  acceptFriendRequest,
  declineFriendRequest,
  updateUserXFriends,
  updateUserXProfileAllScreens,
} from '../../store/actions';

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 {profile = NO_PROFILE, user} = userXId
    ? useSelector((state: RootState) => state.userX[screenType][userXId])
    : useSelector((state: RootState) => state.user);

  const {user: loggedInUser = NO_USER} = useSelector(
    (state: RootState) => state.user,
  );

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

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

  const state: RootState = useStore().getState();
  const dispatch = useDispatch();

  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));
  };

  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>
      )}
      {userXId && !isBlocked && (
        <View style={styles.buttonsContainer}>
          <FriendsButton userXId={userXId} screenType={screenType} />
          {(friendship_status === 'requested' &&
            friendship_requester_id !== userXId && (
              <Button
                title={'Requested'}
                buttonStyle={styles.requestedButton}
                titleStyle={styles.requestedButtonTitle}
                onPress={() =>
                  handleFriendUnfriend(
                    screenType,
                    user,
                    profile,
                    dispatch,
                    state,
                    loggedInUser,
                  )
                } // delete request, no record status
              />
            )) ||
            (friendship_status === 'requested' &&
              friendship_requester_id === userXId && (
                <AcceptDeclineButtons
                  requester={getUserAsProfilePreviewType(
                    {userId: userXId, username},
                    profile,
                  )}
                  onAccept={handleAcceptRequest}
                  onReject={handleDeclineFriendRequest}
                  externalStyles={{container: styles.acceptRejectContainer}}
                />
              ))}
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  toggleButtonContainer: {
    flexDirection: 'row',
    flex: 1,
    paddingTop: '3.5%',
    paddingBottom: '2%',
  },
  acceptRejectContainer: {
    flexDirection: 'row',
  },
  buttonsContainer: {
    flexDirection: 'row',
    flex: 1,
    paddingTop: '3.5%',
    paddingBottom: '2%',
  },
  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%',
  },
  requestedButton: {
    justifyContent: 'center',
    alignItems: 'center',
    width: SCREEN_WIDTH * 0.4,
    height: SCREEN_WIDTH * 0.075,
    borderColor: TAGG_LIGHT_BLUE,
    borderWidth: 2,
    borderRadius: 3,
    marginRight: '2%',
    padding: 0,
    backgroundColor: 'transparent',
  },
  requestedButtonTitle: {
    color: TAGG_LIGHT_BLUE,
    padding: 0,
    fontSize: 14,
    fontWeight: '700',
  },
  buttonTitle: {
    color: 'white',
    padding: 0,
    fontSize: 14,
    fontWeight: '700',
  },
  button: {
    justifyContent: 'center',
    alignItems: 'center',
    width: SCREEN_WIDTH * 0.4,
    height: SCREEN_WIDTH * 0.075,
    padding: 0,
    borderWidth: 2,
    borderColor: TAGG_LIGHT_BLUE,
    borderRadius: 3,
    marginRight: '2%',
    backgroundColor: TAGG_LIGHT_BLUE,
  },
});

export default ProfileBody;
