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

import { AvatarWithInitials } from 'src/components';
import { API_HOST } from 'src/constants';
import { TriumphsStyles } from './styles';
import { TriumphsData } from '../utils/types';
import { useConnection } from 'src/contexts/ConnectionContext';

export const TriumphItem = React.memo(
  ({ item, onPress }: { item: TriumphsData; onPress: (userId: number) => void }) => {
    const netInfo = useConnection();
    const [firstPart, secondPart] = item.text.split(' reached ');
    const [firstName, lastName] = item.name.split(' ');

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

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

    const handlePress = useCallback(() => {
      onPress(item.user_id);
    }, [item.user_id, onPress]);

    return (
      <TouchableOpacity onPress={handlePress} style={TriumphsStyles.itemContainer}>
        {item.avatar && avatarBaseUri ? (
          <View>
            <Image source={{ uri: avatarBaseUri }} style={TriumphsStyles.avatar} />
            <Image source={{ uri: flagBaseUri }} style={TriumphsStyles.flag} />
          </View>
        ) : (
          <AvatarWithInitials
            text={`${firstName[0] ?? ''}${lastName[0] ?? ''}`}
            flag={flagBaseUri}
            size={48}
          />
        )}
        <View style={{ flex: 1 }}>
          <Text style={TriumphsStyles.text}>{item.name}</Text>
          <View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
            <Text style={TriumphsStyles.text}>
              <Text style={TriumphsStyles.reached}>reached </Text>
              <Text>{secondPart}</Text>
            </Text>
          </View>
        </View>

        <View style={TriumphsStyles.tresholdContainer}>
          <Image source={{ uri: API_HOST + item.icon }} style={TriumphsStyles.icon} />
          <Text style={TriumphsStyles.treshold}>{item.treshold}</Text>
        </View>
      </TouchableOpacity>
    );
  }
);
