import React, { ReactNode, useEffect, useMemo } from 'react';
import { useSetAtom } from 'jotai';
import { enviveConfigAtom } from 'src/atoms/envive/enviveConfig';
import Logger from 'src/application/logging/logger';
import { OrgConfigFeatureGate } from 'src/application/models/api/orgConfigResults';
import { EnviveConfig } from '../types';

const logger = new Logger('enviveConfigContext');

interface EnviveConfigProviderProps {
  children: ReactNode;
  amplitudeApiKey?: string;
  dataResidency?: string;
  env?: string;
  baseUrl?: string;
  reactAppName?: string;
  cdnUrl?: string;
  contextSource?: string;
  orgLevelApiKey?: string;
  orgId?: string;
  orgShortName?: string;
  identifyingPrefix: string;
  featureOverrides?: Record<string, boolean>;
  variantUrlOverride?: string;
  variantInfoOverride?: any;
  show?: boolean;
  enviveOn?: boolean;
  publicKey?: string;
  featureGates?: OrgConfigFeatureGate[]; // New prop for feature gates
}

export const EnviveConfigProvider: React.FC<EnviveConfigProviderProps> = ({
  children,
  amplitudeApiKey,
  dataResidency,
  env,
  baseUrl,
  reactAppName,
  cdnUrl,
  contextSource,
  orgLevelApiKey,
  orgShortName,
  orgId,
  identifyingPrefix,
  featureOverrides,
  variantUrlOverride,
  variantInfoOverride,
  show,
  enviveOn,
  publicKey,
  featureGates, // Destructure new prop
}) => {
  const setEnviveConfig = useSetAtom(enviveConfigAtom);

  const config: EnviveConfig = useMemo(
    () => ({
      amplitudeApiKey,
      dataResidency,
      env,
      baseUrl,
      reactAppName,
      cdnUrl,
      contextSource,
      orgLevelApiKey,
      orgShortName,
      orgId,
      identifyingPrefix,
      featureOverrides,
      variantUrlOverride,
      variantInfoOverride,
      show,
      enviveOn,
      publicKey,
      featureGates,
    }),
    [
      amplitudeApiKey,
      dataResidency,
      env,
      baseUrl,
      reactAppName,
      cdnUrl,
      contextSource,
      orgLevelApiKey,
      orgShortName,
      orgId,
      identifyingPrefix,
      featureOverrides,
      variantUrlOverride,
      variantInfoOverride,
      show,
      enviveOn,
      publicKey,
      featureGates,
    ],
  );

  useEffect(() => {
    setEnviveConfig(config);
    logger.logDebug('EnviveConfigProvider: Setting EnviveConfig', config);
  }, [setEnviveConfig, config]);

  if (!config) {
    return null;
  }
  return children;
};
