import { useAtomValue } from 'jotai';
import { Dispatch, ReactNode, SetStateAction, createContext, useMemo, useState } from 'react';
import { GenerationParams } from 'src/application/models';
import { baseUrlAtom } from 'src/atoms/envive/enviveConfig';

// TODO: Refactor this to a common service that handles query params (and spiffy variables all together)
const getChatModelName = () => {
  const urlObj = new URL(window.location.href);
  const params = new URLSearchParams(urlObj.search);
  const paramsObj = Object.fromEntries(params.entries());
  return paramsObj.llm_model_name;
};

const defaultGenerationParams: GenerationParams = {
  stream: true,
  numSuggestions: 3,
  model: getChatModelName(),
};

interface SystemSettingsContextParams {
  generationParams?: GenerationParams;
  showDebugBar?: boolean;
  endpointURL?: string;
  setGenerationParams: Dispatch<SetStateAction<GenerationParams | undefined>>;
}

interface SystemSettingsContextProviderProps {
  children: ReactNode;
  generationParams?: GenerationParams;
  showDebugBar?: boolean;
}

const SystemSettingsContext = createContext<SystemSettingsContextParams | undefined>(undefined);

const SystemSettingsContextProvider = ({
  children,
  generationParams,
  showDebugBar,
}: SystemSettingsContextProviderProps) => {
  const [params, setParams] = useState<GenerationParams | undefined>(
    () => generationParams ?? defaultGenerationParams,
  );
  const endpointURL = useAtomValue(baseUrlAtom);
  const settingsContextValues = useMemo(
    () => ({
      generationParams: params,
      showDebugBar,
      setGenerationParams: setParams,
      endpointURL,
    }),
    [generationParams, endpointURL, showDebugBar],
  );

  return (
    <SystemSettingsContext.Provider value={settingsContextValues}>
      {children}
    </SystemSettingsContext.Provider>
  );
};

export { SystemSettingsContextProvider, SystemSettingsContext, defaultGenerationParams };
