import React, { useEffect } from 'react';
import setDefaultOptions from 'date-fns/setDefaultOptions';
import { LocaleContext } from './context';
import { getDateFnsLocale } from './utils';
import type { LocaleValues } from '../../locales/types';

interface LocaleProviderProps {
  locale: LocaleValues;
}

const LocaleProvider = (
  props: React.PropsWithChildren<LocaleProviderProps>
) => {
  const { locale, children } = props;
  const code = locale?.['lang'] || 'en-AU';
  // setDefaultOptions here instead of inside useEffect for first rendering
  setDefaultOptions({ locale: getDateFnsLocale(code) });
  useEffect(() => {
    return () => setDefaultOptions({ locale: getDateFnsLocale('en-AU') });
  }, []);

  return (
    <LocaleContext.Provider value={locale}>{children}</LocaleContext.Provider>
  );
};

export default LocaleProvider;
