import { config, createConfig, type SDKConfig } from '@lifi/sdk';
import { createContext, useContext, useEffect, useId, useMemo } from 'react';
import { version } from '../../config/version.js';
import { setDefaultSettings } from '../../stores/settings/useSettingsStore.js';
import type { WidgetContextProps, WidgetProviderProps } from './types.js';
// import { attemptToFindMatchingToAddressInConfig } from './utils.js';
import mixpanel from 'mixpanel-browser';
import * as Sentry from '@sentry/react';

const initialContext: WidgetContextProps = {
  elementId: '',
  integrator: '',
};

const WidgetContext = createContext<WidgetContextProps>(initialContext);

export const useWidgetConfig = (): WidgetContextProps =>
  useContext(WidgetContext);

let sdkInitialized = false;

export const WidgetProvider: React.FC<
  React.PropsWithChildren<WidgetProviderProps>
> = ({ children, config: widgetConfig }) => {
  const elementId = useId();

  if (!widgetConfig?.integrator) {
    throw Error('Required property "integrator" is missing.');
  }

  useEffect(() => {
    if (widgetConfig?.mixpanelToken) {
      mixpanel.init(widgetConfig.mixpanelToken, {
        debug: false,
        ignore_dnt: true,
      });
    }
  }, [widgetConfig?.mixpanelToken]);

  useEffect(() => {
    Sentry.init({
      dsn: 'https://314310ebdb5bff4a14a386f1eb6d47b2@o4505729367801856.ingest.us.sentry.io/4506455493246976',
      integrations: [Sentry.browserTracingIntegration()],
      tracesSampleRate: 0,
      sampleRate: 0.1,
    });
  }, []);

  const value = useMemo((): WidgetContextProps => {
    try {
      // Create widget configuration object
      const value = {
        ...widgetConfig,
        elementId,
      } as WidgetContextProps;

      // Set default settings for widget settings store
      setDefaultSettings(value);

      // Configure SDK
      const _config: SDKConfig = {
        ...widgetConfig.sdkConfig,
        apiKey: widgetConfig.apiKey,
        integrator: widgetConfig.integrator ?? window?.location.hostname,
        routeOptions: {
          fee: widgetConfig.feeConfig?.fee || widgetConfig.fee,
          referrer: widgetConfig.referrer,
          order: widgetConfig.routePriority,
          slippage: widgetConfig.slippage,
          ...widgetConfig.sdkConfig?.routeOptions,
        },
        disableVersionCheck: true,
        widgetVersion: version,
        preloadChains: false,
      };
      if (!sdkInitialized) {
        createConfig(_config);
        sdkInitialized = true;
      } else {
        config.set(_config);
      }

      return value;
    } catch (e) {
      console.warn(e);
      return {
        ...widgetConfig,
        elementId,
        integrator: widgetConfig.integrator,
      };
    }
  }, [elementId, widgetConfig]);
  return (
    <WidgetContext.Provider value={value}>{children}</WidgetContext.Provider>
  );
};
