import React, {useEffect} from 'react';
import {createContext, useState} from 'react';
import AsyncStorage from '@react-native-community/async-storage';
import {UserType, ProfileType, InstagramPostType} from '../../types';

import {
  loadProfileInfo,
  loadAvatar,
  loadCover,
  loadInstaPosts,
  loadRecentlySearchedUsers,
} from '../../services';

interface ProfileContextProps {
  user: UserType;
  profile: ProfileType;
  loadProfile: (userId: string, username: string) => void;
  avatar: string | null;
  cover: string | null;
  instaPosts: Array<InstagramPostType>;
}
const NO_USER: UserType = {
  userId: '',
  username: '',
};
const NO_PROFILE: ProfileType = {
  biography: '',
  website: '',
  name: '',
};
export const ProfileContext = createContext<ProfileContextProps>({
  user: NO_USER,
  profile: NO_PROFILE,
  loadProfile: () => {},
  avatar: null,
  cover: null,
  instaPosts: [],
});

/**
 * 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 [instaPosts, setInstaPosts] = useState<Array<InstagramPostType>>([]);

  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);
        loadInstaPosts(token, userId, setInstaPosts);
      } catch (err) {
        console.log(err);
      }
    };
    loadData();
  }, [userId]);

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

export default ProfileProvider;
