import { createContext, useReducer, useContext } from "react";

const initialState = {
  email: "",
  password: "",
};

const ACTION_TYPES = {
  SET_USER_PROPERTIES: "SET_USER_PROPERTIES",
  CLEAR_USER_PROPERTIES: "CLEAR_USER_PROPERTIES",
};

function userPropertiesReducer(state, action) {
  switch (action.type) {
    case ACTION_TYPES.SET_USER_PROPERTIES:
      return { ...state, ...action.payload };
    case ACTION_TYPES.CLEAR_USER_PROPERTIES:
      return { ...initialState };
    default:
      return state;
  }
}

const UserPropertiesContext = createContext(undefined);

export function UserPropertiesProvider({ children }) {
  const [state, dispatch] = useReducer(userPropertiesReducer, initialState);

  return (
    <UserPropertiesContext.Provider value={{ state, dispatch, ACTION_TYPES }}>
      {children}
    </UserPropertiesContext.Provider>
  );
}

export function useUserProperties() {
  const context = useContext(UserPropertiesContext);
  if (context === undefined) {
    throw new Error(
      "useUserProperties must be used within a UserPropertiesProvider",
    );
  }
  return context;
}
