import React, {useEffect} from 'react';
import {createContext, useState} from 'react';
import {
  UserType,
  ProfileType,
  InstagramPostType,
  ProfilePreviewType,
} from '../../types';
import AsyncStorage from '@react-native-community/async-storage';
import {
  loadProfileInfo,
  loadAvatar,
  loadCover,
  loadInstaPosts,
  loadRecentlySearchedUsers,
} from '../../services';

interface AuthContextProps {
  user: UserType;
  profile: ProfileType;
  login: (userId: string, username: string) => void;
  logout: () => void;
  avatar: string | null;
  cover: string | null;
  instaPosts: Array<InstagramPostType>;
  recentSearches: Array<ProfilePreviewType>;
  newMomentsAvailable: boolean;
  updateMoments: (value: boolean) => void;
}
const NO_USER: UserType = {
  userId: '',
  username: '',
};
const NO_PROFILE: ProfileType = {
  biography: '',
  website: '',
  name: '',
};
export const AuthContext = createContext<AuthContextProps>({
  user: NO_USER,
  profile: NO_PROFILE,
  login: () => {},
  logout: () => {},
  avatar: null,
  cover: null,
  instaPosts: [],
  recentSearches: [],
  newMomentsAvailable: true,
  updateMoments: () => {},
});

/**
 * Authentication provider for the application.
 */
const AuthProvider: 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 [recentSearches, setRecentSearches] = useState<
    Array<ProfilePreviewType>
  >([]);
  const [newMomentsAvailable, setNewMomentsAvailable] = useState<boolean>(true);
  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);
        loadRecentlySearchedUsers(setRecentSearches);
      } catch (err) {
        console.log(err);
      }
    };
    loadData();
  }, [userId]);

  return (
    <AuthContext.Provider
      value={{
        user,
        profile,
        avatar,
        cover,
        instaPosts,
        newMomentsAvailable,
        login: (id, username) => {
          setUser({...user, userId: id, username});
        },
        logout: () => {
          try {
            new Promise(() => {
              AsyncStorage.removeItem('token');
            }).then(() => {
              setUser(NO_USER);
            });
          } catch (err) {
            console.log(err);
          }
        },
        recentSearches,
        updateMoments: (value) => {
          setNewMomentsAvailable(value);
        },
      }}>
      {children}
    </AuthContext.Provider>
  );
};

export default AuthProvider;
