import React, { FC, useState } from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { Image } from 'expo-image';
import { useNavigation } from '@react-navigation/native';
import * as FileSystem from 'expo-file-system';

import { ProfileStyles, ScoreStyles, TBTStyles } from './styles';

import { storage, StoreType } from 'src/storage';
import { AvatarWithInitials, WarningModal } from 'src/components';

import { API_HOST } from '../../../../constants';
import { getFontSize } from '../../../../utils';
import { adaptiveStyle } from '../../../../theme';

import TickIcon from '../../../../../assets/icons/tick.svg';
import UNIcon from '../../../../../assets/icons/un_icon.svg';
import NMIcon from '../../../../../assets/icons/nm_icon.svg';
import TBTIcon from '../../../../../assets/icons/tbt.svg';

import { NAVIGATION_PAGES } from '../../../../types';
import { useConnection } from 'src/contexts/ConnectionContext';

type Props = {
  avatar: string;
  first_name: string;
  last_name: string;
  date_of_birth: number;
  homebase_flag: string;
  homebase2_flag: string;
  index: number;
  score: any[];
  active_score: number;
  tbt_score?: number;
  tbt_rank?: number;
  badge_tbt?: number;
  badge_1281: number;
  badge_un: number;
  auth: number;
  userId: number;
};

//TODO: Profile
export const Profile: FC<Props> = ({
  avatar,
  first_name,
  last_name,
  date_of_birth,
  homebase_flag,
  homebase2_flag,
  index,
  score,
  active_score,
  tbt_rank,
  badge_tbt,
  badge_1281,
  badge_un,
  auth,
  userId
}) => {
  const navigation = useNavigation();

  const scoreNames = ['NM', 'DARE', 'UN', 'UN+', 'TCC', 'DEEP', 'YES', 'SLOW', 'WHS', 'KYE'];
  const netInfo = useConnection();
  const token = storage.get('token', StoreType.STRING);
  const [modalType, setModalType] = useState<string | null>(null);

  const handlePress = () => {
    if (!netInfo?.isInternetReachable) {
      setModalType('offline');
    } else if (!token) {
      setModalType('unauthorized');
    } else {
      navigation.navigate(...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId }] as never));
    }
  };

  const avatarBaseUri = netInfo?.isInternetReachable
    ? `${API_HOST}/img/avatars/`
    : `${FileSystem.documentDirectory}avatars/`;

  const flagBaseUri = netInfo?.isInternetReachable
    ? `${API_HOST}/img/flags_new/`
    : `${FileSystem.documentDirectory}flags/`;

  const TBRanking = () => {
    const colors = [
      'rgba(237, 147, 52, 1)',
      'rgba(128, 128, 128, 1)',
      'rgba(211, 211, 211, 1)',
      'rgba(187, 95, 5, 1)',
      '#808080'
    ];

    const Rank = ({ color }: { color: string }) => (
      <View style={adaptiveStyle([ProfileStyles.badge, { backgroundColor: color }], {})}>
        <TBTIcon />
      </View>
    );

    return tbt_rank && tbt_rank >= 1 ? (
      <View style={adaptiveStyle(TBTStyles.badgeRoot, {})}>
        <View style={adaptiveStyle(TBTStyles.badgeWrapper, {})}>
          {badge_tbt ? <Rank color={colors[tbt_rank - 1]} /> : null}
          <Text style={adaptiveStyle([ScoreStyles.scoreNameText], {})}>TBT # {tbt_rank}</Text>
        </View>
      </View>
    ) : null;
  };

  const EmptyScore: FC<{ scoreName: string }> = ({ scoreName }) => {
    return (
      <View style={adaptiveStyle(ScoreStyles.scoreWrapper, {})}>
        <Text style={adaptiveStyle([ScoreStyles.scoreHeaderText], {})}>-</Text>
        <Text style={adaptiveStyle([ScoreStyles.scoreNameText], {})}>{scoreName}</Text>
      </View>
    );
  };

  return (
    <View>
      <TouchableOpacity onPress={() => handlePress()}>
        <View style={adaptiveStyle(ProfileStyles.profileRoot, {})}>
          <View style={{ paddingLeft: 20 }}>
            {index + 1 < 100 ? (
              <View>
                <Text style={adaptiveStyle(ScoreStyles.rankText, {})}>{index + 1}</Text>
              </View>
            ) : null}
            <View style={{ marginLeft: 5 }}>
              {avatar ? (
                <Image
                  style={adaptiveStyle(ProfileStyles.profileAvatar, {})}
                  source={{ uri: avatarBaseUri + avatar }}
                />
              ) : (
                <AvatarWithInitials
                  text={`${first_name[0] ?? ''}${last_name[0] ?? ''}`}
                  flag={flagBaseUri + homebase_flag}
                  size={48}
                />
              )}
            </View>
          </View>
          <View style={adaptiveStyle(ProfileStyles.profileDataRoot, {})}>
            <Text
              style={adaptiveStyle(
                [ProfileStyles.profileFirstLastName, { fontSize: getFontSize(14), flex: 0 }],
                {}
              )}
            >
              {first_name ?? ''} {last_name ?? ''}
            </Text>
            <View style={adaptiveStyle(ProfileStyles.profileDataContainer, {})}>
              <View style={adaptiveStyle(ProfileStyles.profileDataWrapper, {})}>
                <Text style={adaptiveStyle(ProfileStyles.profileAge, {})}>
                  Age: {date_of_birth ?? ''}
                </Text>
                <Image
                  source={{ uri: flagBaseUri + homebase_flag }}
                  style={adaptiveStyle(ProfileStyles.countryFlag, {})}
                />
                {homebase2_flag && homebase2_flag !== homebase_flag ? (
                  <Image
                    source={{ uri: flagBaseUri + homebase2_flag }}
                    style={adaptiveStyle([ProfileStyles.countryFlag, { marginLeft: -15 }], {})}
                  />
                ) : null}
                <View style={adaptiveStyle(ProfileStyles.badgesWrapper, {})}>
                  {auth ? <TickIcon /> : null}
                  {badge_un ? <UNIcon /> : null}
                  {badge_1281 ? <NMIcon /> : null}
                </View>
              </View>
            </View>
          </View>
        </View>
      </TouchableOpacity>
      <View style={adaptiveStyle(ScoreStyles.rankingWrapper, {})}>
        <View style={adaptiveStyle(ScoreStyles.nmWrapper, {})}>
          <Text style={adaptiveStyle(ScoreStyles.activeScoreRanking, {})}>
            {score[active_score]}
          </Text>
          <Text style={adaptiveStyle(ScoreStyles.activeScoreName, {})}>
            {scoreNames[active_score]}
          </Text>
          <TBRanking />
        </View>

        <View style={adaptiveStyle(ScoreStyles.rankingScoresWrapper, {})}>
          {score.map((number, index) => {
            if (scoreNames[index] === 'SLOW' && number >= 4500)
              return <EmptyScore key={index} scoreName={scoreNames[index]} />;
            if (scoreNames[index] === 'YES' && number >= 10000)
              return <EmptyScore key={index} scoreName={scoreNames[index]} />;
            if (!number) return <EmptyScore key={index} scoreName={scoreNames[index]} />;
            return (
              <View key={index} style={adaptiveStyle(ScoreStyles.scoreWrapper, {})}>
                <Text style={adaptiveStyle([ScoreStyles.scoreHeaderText], {})}>{number}</Text>
                <Text style={adaptiveStyle([ScoreStyles.scoreNameText], {})}>
                  {scoreNames[index]}
                </Text>
              </View>
            );
          })}
        </View>
      </View>
      {modalType && (
        <WarningModal
          type={modalType}
          isVisible={true}
          onClose={() => setModalType(null)}
        />
      )}
    </View>
  );
};
