import React from 'react';
import { Text, TouchableOpacity, View, Image, Dimensions } from 'react-native';
import * as FileSystem from 'expo-file-system/legacy';

import { AvatarWithInitials } from '../../../../components';

import { API_HOST } from 'src/constants';
import { getFontSize } from 'src/utils';
import { Colors } from 'src/theme';
import { SeriesRanking } from '../utils/types';
import { ProfileStyles, ScoreStyles } from './styles';
import { useConnection } from 'src/contexts/ConnectionContext';
import formatNumber from '../../TravelsScreen/utils/formatNumber';

import TickIcon from 'assets/icons/tick.svg';
import UNIcon from 'assets/icons/un_icon.svg';
import NMIcon from 'assets/icons/nm_icon.svg';
import UN25Icon from 'assets/icons/un-25.svg';
import UN50Icon from 'assets/icons/un-50.svg';
import UN75Icon from 'assets/icons/un-75.svg';
import UN100Icon from 'assets/icons/un-100.svg';
import UN150Icon from 'assets/icons/un-150.svg';
import ArrowIcon from 'assets/icons/arrow-bold.svg';
import PremiumIcon from 'assets/icons/premium.svg';

const SeriesRankingItem = React.memo(
  ({
    item,
    index,
    onPress
  }: {
    item: SeriesRanking;
    index: number;
    onPress: (userId: number) => void;
  }) => {
    const netInfo = useConnection();
    const isSmallScreen = Dimensions.get('window').width < 383;

    const avatarBaseUri = netInfo?.isInternetReachable ? API_HOST + item.avatar : null;

    const flagBaseUri = (flag: string) =>
      netInfo?.isInternetReachable
        ? API_HOST + flag
        : `${FileSystem.documentDirectory}flags/${flag.split('/').pop()}`;

    return (
      <TouchableOpacity
        onPress={() => onPress(item.user_id)}
        style={[
          ProfileStyles.profileContainer,
          { backgroundColor: Colors.FILL_LIGHT, padding: 6, borderRadius: 8, marginBottom: 12 }
        ]}
      >
        <View style={[ProfileStyles.profileRoot, { marginBottom: 0 }]}>
          <View style={{ flexDirection: 'row' }}>
            <View
              style={{
                alignItems: 'center',
                justifyContent: 'center',
                width: index + 1 < 100 ? 26 : index + 1 < 1000 ? 38 : 50
              }}
            >
              <Text style={ScoreStyles.rankText}>{index + 1}</Text>
            </View>
            <View style={{ marginLeft: 4, position: 'relative' }}>
              {item.avatar && avatarBaseUri ? (
                <Image style={ProfileStyles.profileAvatar} source={{ uri: avatarBaseUri }} />
              ) : (
                <AvatarWithInitials
                  text={`${item.first_name[0] ?? ''}${item.last_name[0] ?? ''}`}
                  flag={flagBaseUri(item.flag1)}
                  size={48}
                />
              )}
              <View
                style={{
                  position: 'absolute',
                  bottom: 0,
                  right: 0,
                  justifyContent: 'center',
                  alignItems: 'center'
                }}
              >
                {item.badge_premium ? <PremiumIcon width={16} height={16} /> : null}
              </View>
            </View>
          </View>
          <View style={{ gap: 5, flex: 1 }}>
            <Text
              style={[ProfileStyles.profileFirstLastName, { fontSize: getFontSize(14), flex: 0 }]}
            >
              {item.first_name ?? ''} {item.last_name ?? ''}
            </Text>
            <View style={[ProfileStyles.profileDataContainer, { flex: 1 }]}>
              <View style={[ProfileStyles.profileDataWrapper, isSmallScreen ? { gap: 6 } : {}]}>
                <Text style={ProfileStyles.profileAge}>Age: {item.age ?? ''}</Text>
                <Image
                  source={{ uri: flagBaseUri(item.flag1) }}
                  style={ProfileStyles.countryFlag}
                />
                {item.flag2 && item.flag2 !== item.flag1 ? (
                  <Image
                    source={{ uri: flagBaseUri(item.flag2) }}
                    style={[ProfileStyles.countryFlag, { marginLeft: -15 }]}
                  />
                ) : null}
                <View style={[ProfileStyles.badgesWrapper, isSmallScreen ? { marginLeft: 4 } : {}]}>
                  {item.authenticated === 1 ? <TickIcon /> : null}
                  {item.badge_un === 1 ? <UNIcon /> : null}
                  {item.badge_nm === 1 ? <NMIcon /> : null}
                  {item.badge_un_150 ? <UN150Icon /> : null}
                  {item.badge_un_100 ? <UN100Icon /> : null}
                  {item.badge_un_75 ? <UN75Icon /> : null}
                  {item.badge_un_50 ? <UN50Icon /> : null}
                  {item.badge_un_25 ? <UN25Icon /> : null}
                </View>
              </View>

              <View style={[ProfileStyles.rightScore, { flex: 1, justifyContent: 'flex-end' }]}>
                <Text
                  style={[
                    {
                      fontWeight: 'bold',
                      fontSize: isSmallScreen ? 12 : 16
                    },
                    item.recent_score_increase
                      ? { color: Colors.ORANGE }
                      : { color: Colors.DARK_BLUE }
                  ]}
                >
                  {isSmallScreen ? formatNumber(item.score) : item.score}
                </Text>
                {item.recent_score_increase ? (
                  <ArrowIcon stroke={Colors.ORANGE} />
                ) : (
                  <View style={{ width: 10 }}></View>
                )}
              </View>
            </View>
          </View>
        </View>
      </TouchableOpacity>
    );
  }
);

export default SeriesRankingItem;
