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 Tooltip from 'react-native-walkthrough-tooltip';
import { FilterImage } from 'react-native-svg/filter-image';

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, Colors } from '../../../../theme';

import TickIcon from '../../../../../assets/icons/TickIcon';
import UNIcon from '../../../../../assets/icons/UNIcon';
import NMIcon from '../../../../../assets/icons/NMIcon';
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 TBTIcon from '../../../../../assets/icons/tbt.svg';
import MonumentIcon from '../../../../../assets/icons/monument.svg';
import PremiumIcon from 'assets/icons/premium.svg';

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

type Props = {
  avatar: string | null;
  first_name: string;
  last_name: string;
  date_of_birth: number;
  homebase_flag: string;
  homebase2_flag: string | null;
  index: number;
  score: any[];
  active_score: number;
  tbt_score?: number;
  tbt_rank?: number;
  badge_tbt?: number;
  badge_1281: number;
  badge_un: number;
  badge_un_25: number;
  badge_un_50: number;
  badge_un_75: number;
  badge_un_100: number;
  badge_un_150: number;
  badge_premium: 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,
  badge_un_25,
  badge_un_50,
  badge_un_75,
  badge_un_100,
  badge_un_150,
  badge_premium,
  auth,
  userId
}) => {
  const navigation = useNavigation();

  const scoreNames = ['NM', 'UN', 'UN+', 'DARE', 'TCC', 'DEEP', 'SLOW', 'YES', 'KYE', 'WHS'];

  const netInfo = useConnection();
  const token = storage.get('token', StoreType.STRING);
  const [modalType, setModalType] = useState<string | null>(null);
  const [toolTipVisible, setToolTipVisible] = useState<number | 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/` : null;

  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 (
      <Tooltip
        isVisible={toolTipVisible === 'TBT'}
        content={<Text style={{ color: Colors.DARK_BLUE }}>{handleGetTooltip('TBT')}</Text>}
        contentStyle={{ backgroundColor: Colors.WHITE }}
        placement="top"
        onClose={() => setToolTipVisible(null)}
        backgroundColor="transparent"
        allowChildInteraction={false}
        parentWrapperStyle={adaptiveStyle(TBTStyles.badgeRoot, {})}
      >
        <TouchableOpacity
          style={{ flex: 1 }}
          disabled={!tbt_rank || tbt_rank < 1}
          onPress={() => setToolTipVisible('TBT')}
        >
          <View style={adaptiveStyle(TBTStyles.badgeWrapper, {})}>
            {badge_tbt && tbt_rank ? (
              <Rank color={colors[tbt_rank - 1]} />
            ) : (
              <View style={adaptiveStyle(ProfileStyles.badge, {})} />
            )}
            {tbt_rank && tbt_rank >= 1 ? (
              <Text style={adaptiveStyle([ScoreStyles.scoreNameText], {})}>TBT # {tbt_rank}</Text>
            ) : (
              <View style={{ height: 11 }} />
            )}
          </View>
        </TouchableOpacity>
      </Tooltip>
    );
  };

  const EmptyScore: FC<{ scoreName: string; index: number }> = ({ scoreName, index }) => {
    return (
      <Tooltip
        isVisible={toolTipVisible === index}
        content={<Text style={{ color: Colors.DARK_BLUE }}>{handleGetTooltip(scoreName)}</Text>}
        contentStyle={{ backgroundColor: Colors.WHITE }}
        placement="top"
        onClose={() => setToolTipVisible(null)}
        backgroundColor="transparent"
        allowChildInteraction={false}
        parentWrapperStyle={adaptiveStyle(ScoreStyles.scoreWrapper, {})}
      >
        <TouchableOpacity onPress={() => setToolTipVisible(index)}>
          <Text style={adaptiveStyle([ScoreStyles.scoreHeaderText], {})}>-</Text>
          <Text style={adaptiveStyle([ScoreStyles.scoreNameText], {})}>{scoreName}</Text>
        </TouchableOpacity>
      </Tooltip>
    );
  };

  const handleGetTooltip = (score: string) => {
    switch (score) {
      case 'NM':
        return 'NM list of regions';
      case 'DARE':
        return (
          <Text>
            <Text style={{ fontWeight: '700' }}>D</Text>istinctive{' '}
            <Text style={{ fontWeight: '700' }}>A</Text>lternative{' '}
            <Text style={{ fontWeight: '700' }}>R</Text>emote{' '}
            <Text style={{ fontWeight: '700' }}>E</Text>
            xtreme places
          </Text>
        );
      case 'UN':
        return 'UN countries';
      case 'UN+':
        return 'UN countries and territories';
      case 'TCC':
        return (
          <Text>
            <Text style={{ fontStyle: 'italic' }}>Travelers’ Century Club</Text> list
          </Text>
        );
      case 'DEEP':
        return (
          <Text>
            <Text style={{ fontWeight: '700' }}>D</Text>efinite{' '}
            <Text style={{ fontWeight: '700' }}>E</Text>xhaustive{'\n'}
            <Text style={{ fontWeight: '700' }}>E</Text>xploring{' '}
            <Text style={{ fontWeight: '700' }}>P</Text>
            roportion{'\n'}NM regions to UN countries ratio{'\n'}
            <Text style={{ fontSize: 11 }}>
              For travellers with minimum 30 UN countries visited.
            </Text>
          </Text>
        );
      case 'YES':
        return 'Years Elapsed Since list';
      case 'SLOW':
        return 'SLOW travel list';
      case 'WHS':
        return 'World Heritage Sites';
      case 'KYE':
        return 'Know Your Earth geographic based list';
      case 'TBT':
        return 'The Biggest Travellers based on all rankings';
    }
    return score;
  };

  return (
    <View style={ProfileStyles.wrapper}>
      <View
        style={[
          ProfileStyles.index,
          {
            width: index + 1 < 100 ? 26 : index + 1 < 1000 ? 38 : index + 1 < 10000 ? 44 : 46
          }
        ]}
      >
        {index === -1 ? (
          <MonumentIcon fill={Colors.DARK_BLUE} />
        ) : (
          <Text
            style={[
              adaptiveStyle(ScoreStyles.rankText, {}),
              { fontSize: index + 1 < 100 ? 18 : index + 1 < 1000 ? 17 : 14 }
            ]}
          >
            {index + 1}
          </Text>
        )}
      </View>
      <View style={{ flex: 1, paddingLeft: 8, paddingRight: 3, paddingBottom: 3 }}>
        <TouchableOpacity onPress={() => handlePress()}>
          <View style={adaptiveStyle(ProfileStyles.profileRoot, {})}>
            <View style={ProfileStyles.avatarContainer}>
              <View style={{ position: 'relative' }}>
                {avatar && avatarBaseUri ? (
                  <FilterImage
                    source={{ uri: avatarBaseUri + avatar }}
                    style={[
                      adaptiveStyle(ProfileStyles.profileAvatar, {}),
                      {
                        filter: index === -1 ? 'grayscale(100%)' : 'grayscale(0)'
                      }
                    ]}
                  />
                ) : homebase_flag ? (
                  <AvatarWithInitials
                    text={`${first_name[0] ?? ''}${last_name[0] ?? ''}`}
                    flag={flagBaseUri + homebase_flag}
                    size={48}
                    grayscale={index === -1}
                  />
                ) : null}
                <View
                  style={{
                    position: 'absolute',
                    bottom: 0,
                    right: 0,
                    justifyContent: 'center',
                    alignItems: 'center'
                  }}
                >
                  {badge_premium ? <PremiumIcon width={16} height={16} /> : null}
                </View>
              </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>
                  {homebase_flag && (
                    <FilterImage
                      source={{ uri: flagBaseUri + homebase_flag }}
                      style={[
                        adaptiveStyle(ProfileStyles.countryFlag, {}),
                        {
                          filter: index === -1 ? 'grayscale(100%)' : 'grayscale(0)'
                        }
                      ]}
                    />
                  )}
                  {homebase2_flag && homebase2_flag !== homebase_flag ? (
                    <FilterImage
                      source={{ uri: flagBaseUri + homebase2_flag }}
                      style={[
                        adaptiveStyle([ProfileStyles.countryFlag, { marginLeft: -15 }], {}),
                        {
                          filter: index === -1 ? 'grayscale(100%)' : 'grayscale(0)'
                        }
                      ]}
                    />
                  ) : null}
                  <View style={adaptiveStyle(ProfileStyles.badgesWrapper, {})}>
                    {auth ? <TickIcon isBlackAndWhite={index === -1} /> : null}
                    {badge_un ? <UNIcon isBlackAndWhite={index === -1} /> : null}
                    {badge_1281 ? <NMIcon isBlackAndWhite={index === -1} /> : null}
                    {badge_un_150 ? <UN150Icon /> : null}
                    {badge_un_100 ? <UN100Icon /> : null}
                    {badge_un_75 ? <UN75Icon /> : null}
                    {badge_un_50 ? <UN50Icon /> : null}
                    {badge_un_25 ? <UN25Icon /> : null}
                  </View>
                </View>
              </View>
            </View>
          </View>
        </TouchableOpacity>
        <View style={adaptiveStyle(ScoreStyles.rankingWrapper, {})}>
          <View style={adaptiveStyle(ScoreStyles.nmWrapper, {})}>
            <View style={ScoreStyles.score}>
              <Text style={adaptiveStyle(ScoreStyles.activeScoreRanking, {})}>
                {score[active_score]}
              </Text>
              <Text style={adaptiveStyle(ScoreStyles.activeScoreName, {})}>
                {scoreNames[active_score]}
              </Text>
            </View>
            <TBRanking />
          </View>

          <View style={adaptiveStyle(ScoreStyles.rankingScoresWrapper, {})}>
            {score.map((number, index) => {
              if (scoreNames[index] === 'SLOW' && number >= 4500)
                return <EmptyScore key={index} scoreName={scoreNames[index]} index={index} />;
              if (scoreNames[index] === 'YES' && number >= 10000)
                return <EmptyScore key={index} scoreName={scoreNames[index]} index={index} />;
              if (!number)
                return <EmptyScore key={index} scoreName={scoreNames[index]} index={index} />;
              return (
                <Tooltip
                  isVisible={toolTipVisible === index}
                  content={
                    <Text style={{ color: Colors.DARK_BLUE }}>
                      {handleGetTooltip(scoreNames[index])}
                    </Text>
                  }
                  contentStyle={{ backgroundColor: Colors.WHITE }}
                  placement="top"
                  onClose={() => setToolTipVisible(null)}
                  backgroundColor="transparent"
                  allowChildInteraction={false}
                  key={index}
                  parentWrapperStyle={adaptiveStyle(ScoreStyles.scoreWrapper, {})}
                >
                  <TouchableOpacity onPress={() => setToolTipVisible(index)}>
                    <Text style={adaptiveStyle([ScoreStyles.scoreHeaderText], {})}>{number}</Text>
                    <Text style={adaptiveStyle([ScoreStyles.scoreNameText], {})}>
                      {scoreNames[index]}
                    </Text>
                  </TouchableOpacity>
                </Tooltip>
              );
            })}
          </View>
        </View>
      </View>
      {modalType && (
        <WarningModal type={modalType} isVisible={true} onClose={() => setModalType(null)} />
      )}
    </View>
  );
};
