import { ICreateI18nProviderData, createI18nProvider } from './createI18nProvider';
import { useMemoizedObject } from '@/hooks';
import { I18nProvider } from 'ra-core';
import { useEffect, useState } from 'react';

function useI18nProvider(data: ICreateI18nProviderData): undefined | I18nProvider | { error: boolean } {
  const [provider, setProvider] = useState<undefined | I18nProvider | { error: boolean }>();
  const memoizedData = useMemoizedObject(data);

  useEffect(() => {
    if (data.customProvider !== undefined) {
      data.customProvider.then(setProvider);
      return;
    }
    createI18nProvider(memoizedData)
      .then((provider) => {
        setProvider(provider);
      })
      .catch(() => {
        setProvider({ error: true });
      });
  }, [memoizedData, data?.customProvider]);

  return provider;
}

export { useI18nProvider };
