"use client";

import { PropsWithChildren, createContext, useReducer
  // , useState
} from "react";

// interface IFavoriteContext {
//   favorites: Array<IMovieSearch>
//   setFavorites: (value: Array<IMovieSearch>) => void
// }
// export const FavoriteContext = createContext<IFavoriteContext>({
//   favorites: [],
//   setFavorites: (_value: Array<IMovieSearch>) => { },
// });

// // Using interleaving to render this context provider client-side, but still utilize server-side renderung for children components
// export const FavoriteProvider = ({ children }: PropsWithChildren) => {
//   const [favorites, setFavorites] = useState<Array<IMovieSearch>>([])
//   return (
//     <FavoriteContext.Provider value={{ favorites, setFavorites }}>{children}</FavoriteContext.Provider>
//   )
// }

interface IFavoriteContext {
  favorites: FavoriteState;
  dispatch: React.Dispatch<FavoriteAction>;
}

type FavoriteState = Array<IMovieSearch>;
type FavoriteAction = { type: "Add" | "Remove"; payload: IMovieSearch };

function FavoriteReducer(state: FavoriteState, action: FavoriteAction) {
  switch (action.type) {
    case "Add":
      state = [...state, action.payload];
      break;
    case "Remove":
      state = state.filter((s) => s.imdbID != action.payload.imdbID);
    default:
      break;
  }
  return state;
}

const initialState: FavoriteState = [];

export const FavoriteContext = createContext<IFavoriteContext>({
  favorites: initialState,
  dispatch: () => null,
});

export function FavoriteProvider({ children }: PropsWithChildren) {
  const [favorites, dispatch] = useReducer(FavoriteReducer, initialState);
  return (
    <FavoriteContext.Provider value={{ favorites, dispatch }}>
      {children}
    </FavoriteContext.Provider>
  );
}
