import {useNavigation} from '@react-navigation/native';
import React from 'react';
import {StyleSheet, Text, View, ViewProps} from 'react-native';
import {TouchableOpacity} from 'react-native-gesture-handler';
import {useSelector, useStore} from 'react-redux';
import {RootState} from '../../store/rootReducer';
import {ScreenType} from '../../types';
import {canViewProfile, normalize} from '../../utils';

interface FriendsCountProps extends ViewProps {
  userXId: string | undefined;
  screenType: ScreenType;
}

const FriendsCount: React.FC<FriendsCountProps> = ({
  style,
  userXId,
  screenType,
}) => {
  const {friends} = useSelector((state: RootState) =>
    userXId ? state.userX[screenType][userXId] : state.friends,
  );
  const count = friends ? friends.length : 0;

  const displayedCount: string =
    count < 5e3
      ? `${count}`
      : count < 1e5
      ? `${(count / 1e3).toFixed(1)}k`
      : count < 1e6
      ? `${(count / 1e3).toFixed(0)}k`
      : `${count / 1e6}m`;

  const navigation = useNavigation();
  const state: RootState = useStore().getState();

  return (
    <TouchableOpacity
      onPress={() =>
        navigation.push('FriendsListScreen', {
          userXId,
          screenType,
        })
      }
      disabled={
        !canViewProfile(state, userXId, screenType) || friends.length === 0
      }>
      <View style={[styles.container, style]}>
        <Text style={styles.count}>{displayedCount}</Text>
        <Text style={styles.label}>Friends</Text>
      </View>
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
  },
  count: {
    fontWeight: '700',
    fontSize: normalize(14),
  },
  label: {
    marginTop: 4,
    fontWeight: '500',
    fontSize: normalize(14),
  },
});

export default FriendsCount;
