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 { storage, StoreType } from 'src/storage';
import { AvatarWithInitials, WarningModal } from 'src/components';

import TickIcon from 'assets/icons/tick.svg';
import UNIcon from 'assets/icons/un_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 NMIcon from 'assets/icons/nm_icon.svg';
import DotsIcon from 'assets/icons/messages/dots-vertical.svg';
import PremiumIcon from 'assets/icons/premium.svg';

import { useConnection } from 'src/contexts/ConnectionContext';
import { NAVIGATION_PAGES } from 'src/types';
import { API_HOST } from 'src/constants';
import { adaptiveStyle, Colors } from 'src/theme';
import {
  ProfileStyles,
  ScoreStyles
} from 'src/screens/InAppScreens/TravellersScreen/Components/styles';
import { getFontSize } from 'src/utils';
import { SheetManager } from 'react-native-actions-sheet';

type Props = {
  admin: 0 | 1;
  canChangeAdmin: boolean;
  groupToken: string;
  refetch: () => void;
  refetchMembers: () => void;
  setIsWarningVisible: (data: any) => void;
  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;
};

export const Profile: FC<Props> = ({
  admin,
  canChangeAdmin,
  groupToken,
  refetch,
  refetchMembers,
  setIsWarningVisible,
  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', 'TBT'];
  const netInfo = useConnection();
  const token = storage.get('token', StoreType.STRING);
  const currentUserId = storage.get('uid', StoreType.STRING) as 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, hideTabBar: true }] as never)
      );
    }
  };

  return (
    <View style={ProfileStyles.wrapper}>
      <TouchableOpacity
        onPress={() => handlePress()}
        style={{ flex: 1, paddingHorizontal: 8, paddingVertical: 3 }}
      >
        <View style={adaptiveStyle(ProfileStyles.profileRoot, {})}>
          <View style={{ position: 'relative' }}>
            {avatar ? (
              <Image
                style={adaptiveStyle(ProfileStyles.profileAvatar, {})}
                source={{ uri: API_HOST + avatar }}
              />
            ) : homebase_flag ? (
              <AvatarWithInitials
                text={`${first_name[0] ?? ''}${last_name[0] ?? ''}`}
                flag={API_HOST + homebase_flag}
                size={48}
              />
            ) : null}
            <View
              style={{
                position: 'absolute',
                bottom: 0,
                right: 0,
                justifyContent: 'center',
                alignItems: 'center'
              }}
            >
              {badge_premium ? <PremiumIcon width={16} height={16} /> : null}
            </View>
          </View>
          <View style={adaptiveStyle(ProfileStyles.profileDataRoot, {})}>
            <View
              style={{
                flexDirection: 'row',
                flex: 1,
                alignItems: 'center',
                gap: 5,
                maxWidth: '85%'
              }}
            >
              <Text
                style={adaptiveStyle(
                  [ProfileStyles.profileFirstLastName, { fontSize: getFontSize(14), flex: 0 }],
                  {}
                )}
              >
                {first_name ?? ''} {last_name ?? ''}
              </Text>
              {admin === 1 && (
                <View
                  style={{
                    justifyContent: 'center',
                    alignItems: 'center',
                    backgroundColor: Colors.ORANGE,
                    height: 12,
                    width: 38,
                    borderRadius: 3
                  }}
                >
                  <Text
                    style={{
                      color: Colors.WHITE,
                      fontSize: getFontSize(10),
                      fontWeight: '600',
                      textAlign: 'center'
                    }}
                  >
                    Admin
                  </Text>
                </View>
              )}
            </View>

            <View style={adaptiveStyle(ProfileStyles.profileDataContainer, {})}>
              <View style={adaptiveStyle(ProfileStyles.profileDataWrapper, {})}>
                <Text style={adaptiveStyle(ProfileStyles.profileAge, {})}>
                  Age: {date_of_birth ?? ''}
                </Text>
                {homebase_flag && (
                  <Image
                    source={{ uri: API_HOST + homebase_flag }}
                    style={adaptiveStyle(ProfileStyles.countryFlag, {})}
                  />
                )}
                {homebase2_flag && homebase2_flag !== homebase_flag ? (
                  <Image
                    source={{ uri: API_HOST + 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}
                  {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 style={{ alignItems: 'center' }}>
            <Text style={adaptiveStyle(ScoreStyles.activeScoreRanking, {})}>
              {score[active_score]}
            </Text>
            <Text style={adaptiveStyle(ScoreStyles.activeScoreName, {})}>
              {scoreNames[active_score]}
            </Text>
          </View>

          {userId !== +currentUserId && canChangeAdmin ? (
            <TouchableOpacity
              style={{ padding: 6 }}
              onPress={() =>
                SheetManager.show('user-options-modal', {
                  payload: {
                    admin: admin,
                    uid: userId,
                    name: first_name + last_name,
                    canChangeAdmin,
                    token,
                    groupToken,
                    refetch,
                    refetchMembers,
                    setIsWarningVisible
                  } as any
                })
              }
              hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
            >
              <DotsIcon />
            </TouchableOpacity>
          ) : canChangeAdmin ? (
            <View style={{ width: 17 }} />
          ) : null}
        </View>
      </TouchableOpacity>
      {modalType && (
        <WarningModal type={modalType} isVisible={true} onClose={() => setModalType(null)} />
      )}
    </View>
  );
};
