import React, { ReactNode, createContext, useContext, useMemo } from 'react';
import { useAtomValue, useSetAtom } from 'jotai';
import { useUIConfig } from 'src/hooks/GraphQLConfig/useGraphQLConfig';
import { orgShortNameAtom } from 'src/atoms/envive/enviveConfig';
import { newOrgConfigAtom } from 'src/atoms/org/newOrgConfigAtom'; // Import newOrgConfigAtom
import { GraphQlConfigValues } from '../graphqlContext';

export type NewOrgConfigContextType = GraphQlConfigValues & {
  loading: boolean;
  error: Error | null;
};

const NewOrgConfigContext = createContext<NewOrgConfigContextType | undefined>(undefined);

interface NewOrgConfigProviderProps {
  children: ReactNode;
  overrideConfig?: GraphQlConfigValues;
}

export const NewOrgConfigProvider: React.FC<NewOrgConfigProviderProps> = ({
  children,
  overrideConfig,
}) => {
  const orgShortName = useAtomValue(orgShortNameAtom);
  const setNewOrgConfig = useSetAtom(newOrgConfigAtom);

  const { data: fetchedConfig, loading, error } = useUIConfig();

  const contextValue = useMemo(() => {
    if (!orgShortName || loading) {
      return { ...fetchedConfig, loading: true, error: null };
    }

    if (error) {
      return { ...fetchedConfig, loading: false, error };
    }

    const activeConfig = overrideConfig || fetchedConfig;

    setNewOrgConfig(activeConfig);
    return { ...activeConfig, loading: false, error: null };
  }, [orgShortName, loading, error, setNewOrgConfig, fetchedConfig, overrideConfig]);

  return (
    <NewOrgConfigContext.Provider value={contextValue}>{children}</NewOrgConfigContext.Provider>
  );
};

export const useNewOrgConfigContext = () => {
  const context = useContext(NewOrgConfigContext);
  if (context === undefined) {
    throw new Error('useNewOrgConfigContext must be used within a NewOrgConfigProvider');
  }
  return context;
};
