import React from 'react';
import hoistStatics from 'hoist-non-react-statics';
import invariant from 'tiny-invariant';

import { ConfigProvider } from 'antd4';

import enUSText from './en-US';
import zhCNText from './zh-CN';

import enUS from 'antd4/lib/locale/en_US';
import zhCN from 'antd4/lib/locale/zh_CN';

interface Props {
  children: React.ReactNode;
  locale: string;
}

interface FMProps {
  id: string;
  defaultMessage: string;
}

export const LocalContext = React.createContext('zh-CN');

export const LocaleProvider = (props: Props) => {
  const { children, locale = 'zh-CN', ...restProps } = props;
  if (window) {
    window.localStorage.setItem('umi_locale', locale);
  }
  return (
    <LocalContext.Provider value={locale}>
      <ConfigProvider locale={locale === 'zh-CN' ? zhCN : enUS} {...restProps}>
        {children}
      </ConfigProvider>
    </LocalContext.Provider>
  );
};

/**
 * 获取当前选择的语言
 * @returns string
 */
export const getLocale = () => {
  const lang =
    typeof localStorage !== 'undefined'
      ? window.localStorage.getItem('umi_locale')
      : '';
  // support baseNavigator, default true
  return lang || 'zh-CN';
};

export const FormattedMessage = (props: FMProps) => {
  const { id, defaultMessage } = props;
  const locale = window.localStorage.getItem('umi_locale') || 'zh-CN';
  const t: any = locale === 'zh-CN' ? zhCNText : enUSText;
  return t?.[id] || defaultMessage || '';
};

export const FM = (props: FMProps) => {
  const { id, defaultMessage } = props;
  return (
    <LocalContext.Consumer>
      {(locale) => {
        const t: any = locale === 'zh-CN' ? zhCNText : enUSText;
        return <>{t?.[id] || defaultMessage}</>;
      }}
    </LocalContext.Consumer>
  );
};
