import { i18n } from '@lingui/core';
import { I18nProvider } from '@lingui/react';
import { ConfigProvider } from 'antd';
import { Locale } from 'antd/es/locale-provider';
import enUS from 'antd/es/locale/en_US';
import viVN from 'antd/es/locale/vi_VN';
import * as React from 'react';
import { useLocalStorage } from 'usehooks-ts';
import { LOCALE_KEY } from '../../consts';
import { dynamicActivate, getLocale } from '../../i18n';

function enhanceAntdViLocale(locale: Locale): Locale {
  return {
    ...locale,
    Text: {
      copied: 'Đã sao chép',
      copy: 'Sao chép',
      edit: 'Chỉnh sửa',
      expand: 'Mở rộng',
    },
  };
}

const antdLocales: Record<string, Locale> = {
  en: enUS,
  vi: enhanceAntdViLocale(viVN),
};

interface InternationalizationProps {
  children: React.ReactNode;
}

const Internationalization = ({ children }: InternationalizationProps) => {
  const [localeStorage] = useLocalStorage(LOCALE_KEY, getLocale());

  React.useEffect(() => {
    dynamicActivate(localeStorage);
  }, [localeStorage]);

  const antdLocale = React.useMemo(
    () => antdLocales[localeStorage],
    [localeStorage],
  );

  return (
    <I18nProvider i18n={i18n} forceRenderOnLocaleChange={false}>
      <ConfigProvider locale={antdLocale}>{children}</ConfigProvider>
    </I18nProvider>
  );
};

export default React.memo(Internationalization);
