import { IntlProvider, ResolvedIntlConfig } from 'react-intl';

import { adjustLocale, DEFAULT_LOCALE, getDirectionFromLocale } from '../common';
import en from '../i18n/en.json';

import { DirectionProvider } from './direction';
import { LanguageProvider } from './language';

export interface ProviderProps {
  i18n: Pick<ResolvedIntlConfig, 'locale' | 'messages'> &
    Partial<Pick<ResolvedIntlConfig, 'defaultRichTextElements'>>;
  children?: React.ReactNode;
}

export default function Provider({ i18n, children }: ProviderProps) {
  const { locale, messages, defaultRichTextElements } = i18n;
  const adjustedLocale = adjustLocale(locale);
  let intlConfig;

  if (adjustedLocale === null) {
    // eslint-disable-next-line no-console
    console.warn(
      `Unsupported locale value was provided: '${locale}', defaulting to '${DEFAULT_LOCALE}'`,
    );

    intlConfig = { locale: DEFAULT_LOCALE, messages: { ...en, ...messages } };
  } else {
    intlConfig = { locale: adjustedLocale, messages };
  }

  return (
    <DirectionProvider direction={getDirectionFromLocale(locale)}>
      <LanguageProvider locale={locale}>
        <IntlProvider
          defaultLocale={DEFAULT_LOCALE}
          locale={intlConfig.locale}
          messages={intlConfig.messages}
          defaultRichTextElements={defaultRichTextElements}
        >
          {children}
        </IntlProvider>
      </LanguageProvider>
    </DirectionProvider>
  );
}
