import AsyncStorage from '@react-native-community/async-storage';
import React, {createContext, useEffect, useState} from 'react';
import {
  GET_IG_POSTS_ENDPOINT,
  GET_TWITTER_POSTS_ENDPOINT,
} from '../../constants';
import {
  loadAvatar,
  loadCover,
  loadProfileInfo,
  loadSocialPosts,
} from '../../services';
import {ProfileType, SocialAccountType, UserType} from '../../types';

interface ProfileContextProps {
  user: UserType;
  profile: ProfileType;
  loadProfile: (userId: string, username: string) => void;
  avatar: string | null;
  cover: string | null;
  newMomentsAvailable: boolean;
  updateMoments: (value: boolean) => void;
  socialAccounts: Record<string, SocialAccountType>;
}
const NO_USER: UserType = {
  userId: '',
  username: '',
};
const NO_PROFILE: ProfileType = {
  biography: '',
  website: '',
  name: '',
};

// Not necessary, but safer, in case SocialAccountType object is undefined
const NO_SOCIAL_ACCOUNTS: Record<string, SocialAccountType> = {
  Instagram: {},
  Facebook: {},
  Twitter: {},
};

export const ProfileContext = createContext<ProfileContextProps>({
  user: NO_USER,
  profile: NO_PROFILE,
  loadProfile: () => {},
  avatar: null,
  cover: null,
  newMomentsAvailable: true,
  updateMoments: () => {},
  socialAccounts: NO_SOCIAL_ACCOUNTS,
});

/**
 * This is the context provider for user profiles that the logged in user wants to see
 */
const ProfileProvider: React.FC = ({children}) => {
  const [user, setUser] = useState<UserType>(NO_USER);
  const [profile, setProfile] = useState<ProfileType>(NO_PROFILE);
  const [avatar, setAvatar] = useState<string | null>(null);
  const [cover, setCover] = useState<string | null>(null);
  const [newMomentsAvailable, setNewMomentsAvailable] = useState<boolean>(true);

  const [socialAccounts, setSocialAccounts] = useState<
    Record<string, SocialAccountType>
  >(NO_SOCIAL_ACCOUNTS);
  const {userId} = user;
  useEffect(() => {
    if (!userId) {
      return;
    }

    const loadData = async () => {
      try {
        const token = await AsyncStorage.getItem('token');
        if (!token) {
          setUser(NO_USER);
          return;
        }
        loadProfileInfo(token, userId, setProfile);
        loadAvatar(token, userId, setAvatar);
        loadCover(token, userId, setCover);
        loadSocialPosts(
          token,
          userId,
          'Instagram',
          GET_IG_POSTS_ENDPOINT,
          socialAccounts,
        ).then((newSocialAccounts) => setSocialAccounts(newSocialAccounts));
        loadSocialPosts(
          token,
          userId,
          'Twitter',
          GET_TWITTER_POSTS_ENDPOINT,
          socialAccounts,
        ).then((newSocialAccounts) => setSocialAccounts(newSocialAccounts));
      } catch (err) {
        console.log(err);
      }
    };
    loadData();
  }, [socialAccounts, userId]);

  return (
    <ProfileContext.Provider
      value={{
        user,
        profile,
        avatar,
        cover,
        newMomentsAvailable,
        socialAccounts,
        loadProfile: (id, username) => {
          setUser({...user, userId: id, username});
        },
        updateMoments: (value) => {
          setNewMomentsAvailable(value);
        },
      }}>
      {children}
    </ProfileContext.Provider>
  );
};

export default ProfileProvider;
