import { useMemo } from 'react';
import {
  ParaProviderCore,
  type ParaProviderBaseProps,
  type ParaClientConfigWithFactory,
  type ParaStorageAdapter,
} from '@getpara/react-core/internal';
import { asyncStorageAdapter } from './asyncStorageAdapter.js';
import { ParaMobile } from '../react-native/ParaMobile.js';

/**
 * React Native Para provider props.
 * paraClientConfig accepts a simple { apiKey, env?, opts? } config or a pre-instantiated ParaMobile instance.
 */
export interface ParaProviderProps extends ParaProviderBaseProps<ParaMobile> {
  /** Override the default AsyncStorage adapter. Defaults to `asyncStorageAdapter`. */
  storageAdapter?: ParaStorageAdapter;
}

/**
 * React Native Para provider. Wraps ParaProviderCore with AsyncStorage-backed
 * persistence by default. Accepts either a ParaMobile instance or a simple
 * `{ apiKey, env?, opts? }` config — the provider creates the client internally.
 */
export function ParaProvider({
  children,
  paraClientConfig: paraClientInput,
  config,
  callbacks,
  storageAdapter = asyncStorageAdapter,
  waitForReady,
  fallback,
}: ParaProviderProps) {
  const coreInput = useMemo<ParaMobile | ParaClientConfigWithFactory<ParaMobile>>(() => {
    if (paraClientInput instanceof ParaMobile) return paraClientInput;
    return {
      ...paraClientInput,
      createClient: (apiKey, env, opts) => new ParaMobile(apiKey, env, opts),
    };
  }, [paraClientInput]);

  return (
    <ParaProviderCore
      paraClientConfig={coreInput}
      config={config}
      callbacks={callbacks}
      storageAdapter={storageAdapter}
      waitForReady={waitForReady}
      fallback={fallback}
    >
      {children}
    </ParaProviderCore>
  );
}
