import { createContext, useContext, useState, FC, ReactNode } from 'react';
import {
  getStorage,
  removeStorage,
  setStorage,
} from '../utils/helpers/storage';
import { UserData } from '../utils/interface/userInterface';

interface Props {
  children: ReactNode;
}

interface IUserContext {
  userStorage: UserData;
}

interface IUserDispatch {
  addUser: (x: UserData) => void;
  clearUser: () => void;
  updateUserInfo: (x: UserData) => void;
}

const UserContext = createContext<IUserContext>({
  userStorage: {} as UserData,
});
const UserDispatchContext = createContext<IUserDispatch>({
  addUser: (userData: UserData) => {},
  clearUser: () => {},
  updateUserInfo: (newUserData: UserData) => {},
});

export const useUserData = () => {
  return useContext(UserContext);
};
export const useUserUpdate = () => {
  return useContext(UserDispatchContext);
};

const useUser = () => {
  const USER_KEY = 'user-data';
  const [userStorage, setUserStorage] = useState(getStorage(USER_KEY));

  const addUser = (userData: UserData) => {
    setStorage(USER_KEY, userData);
    setUserStorage(userData);
  };

  const updateUserInfo = (newUserData: UserData) => {
    setStorage(USER_KEY, newUserData);
    setUserStorage(newUserData);
  };

  const clearUser = () => {
    removeStorage(USER_KEY);
    setUserStorage(null);
  };

  return {
    userStorage,
    addUser,
    updateUserInfo,
    clearUser,
  };
};

const UserProvider: FC<Props> = ({ children }) => {
  const { userStorage, addUser, updateUserInfo, clearUser } = useUser();

  return (
    <UserContext.Provider value={{ userStorage }}>
      <UserDispatchContext.Provider
        value={{
          addUser,
          updateUserInfo,
          clearUser,
        }}
      >
        {children}
      </UserDispatchContext.Provider>
    </UserContext.Provider>
  );
};

export default UserProvider;
