import { PropsWithChildren, createContext, useEffect, useState } from 'react';
import { findMany } from 'helpers';
import { Game } from 'generated/types/prisma.types';

export type BusinessInfo = {
  gameId: string;
  gameName: string;
};
export type BusinessContextType = {
  business: BusinessInfo;
  setBusiness: (business: BusinessInfo) => void;
  businessList: BusinessInfo[];
};

export const BusinessContext = createContext<BusinessContextType>(
  {} as BusinessContextType,
);

export const BusinessContextProvider: React.FC<PropsWithChildren> = ({
  children,
}) => {
  const BusinessFromLocalStorage = JSON.parse(
    localStorage.getItem('Business') ||
      JSON.stringify({
        gameId: 'u10000000066',
        gameName: 'HOK',
      }),
  );

  const [business, setBusiness] = useState<BusinessInfo>(
    BusinessFromLocalStorage,
  );
  const [businessList, setBusinessList] = useState<BusinessInfo[]>([
    BusinessFromLocalStorage,
  ]);

  useEffect(() => {
    window.localStorage.setItem('Business', JSON.stringify(business));
  }, [business]);

  useEffect(() => {
    const fetchGameList = async () => {
      const gameList = await findMany<Game>('game', { take: 1000 });
      setBusinessList(
        gameList.map((game) => ({
          gameId: game.unified_editionid,
          gameName: game.name,
        })),
      );
    };
    fetchGameList();
  }, []);

  return (
    <BusinessContext.Provider
      value={{
        setBusiness,
        business,
        businessList,
      }}
    >
      {children}
    </BusinessContext.Provider>
  );
};
