import AsyncStorage from '@react-native-async-storage/async-storage';
import React, { createContext, FC, ReactElement, useContext, useEffect, useState } from 'react';

type StorageState = [UserInfo, (newInfo: UserInfo) => void];

const StorageContext = createContext<StorageState>(undefined as never);

type props = {
  children: ReactElement;
};

const USER_INFO = 'userInfo';
export type UserInfo = {
  token: string;
  userId: string;
  userName: string;
  personId: string;
  personName: string;
  roleId: string;
  unitId: string;
};

export const StorageProvider: FC<props> = ({ children }) => {
  const [userInfo, setStateUserInfo] = useState<UserInfo>({} as UserInfo);

  useEffect(() => {
    AsyncStorage.getItem(USER_INFO).then(data => {
      if (data) {
        setStateUserInfo(JSON.parse(data));
      }
    });
  }, []);

  const setUserInfo = (newInfo: UserInfo) => {
    setStateUserInfo(newInfo);
    AsyncStorage.setItem(USER_INFO, JSON.stringify(newInfo));
  };

  return (
    <StorageContext.Provider value={[userInfo, setUserInfo]}>{children}</StorageContext.Provider>
  );
};

export const useUserInfo = (): [UserInfo, (newInfo: UserInfo) => void] => {
  const [userInfo, setUserInfo] = useContext(StorageContext);
  return [userInfo, setUserInfo];
};
