import { PropsWithChildren, useState, useEffect } from 'react';
import { useLaunch } from '@tarojs/taro';
import { IntlProvider } from 'react-intl';
import { ConfigProvider, Button } from 'antd';
import { Provider } from 'react-redux';
import store from './states/store';
import { initializeProductState } from './states/productSlice';
import './app.css';
import { lightTheme, darkTheme } from './themes';
import ProductSelector from './components/ProductSelector';
import QuotaAlertModal from './pages/security/QuotaAlertModal';

const locale = (window.navigator.language || 'en').toLowerCase().split('-')[0]; // Get locale from browser or default to 'en'
import messages_en from './assets/i18n/messages/en';
import messages_zh from './assets/i18n/messages/zh';
import AcquisitionTracer from './pages/exam/components/acquisitionTracer';

const messages = locale === 'zh' ? messages_zh : messages_en;
console.log(`process.env.USE_MSW: ${process.env.USE_MSW}`);
console.log(`process.env.NODE_ENV: ${process.env.NODE_ENV}`);

if (process.env.NODE_ENV === 'development' && process.env.USE_MSW === 'true') {
  import('../mocks/server')
    .then(({ server }) => {
      server.start({
        onUnhandledRequest: 'error', // 未处理的请求触发网络错误
      });
      console.log(`启动了MSW`);
    })
    .catch((err) => {
      console.warn('Mock server module not found:', err);
    });
}

function App({ children }: PropsWithChildren<React.ReactNode>) {
  useLaunch(() => {
    console.log('App launched.');
  });

  const [currentTheme, setCurrentTheme] = useState(lightTheme); // 默认使用 light 主题
  const changeTheme = (themeConfig: typeof lightTheme) => {
    setCurrentTheme(themeConfig);
  };

  useEffect(() => {
    store.dispatch(initializeProductState());
  }, []);

  // children 是将要会渲染的页面
  // return children
  return (
    <Provider store={store}>
      <ConfigProvider theme={currentTheme}>
        <IntlProvider locale={locale} messages={messages}>
          <style>
            {/*把theme中的colorPrimary转换成变量--color-primary，变量被tailwindcss使用*/}
            {`:root {
            --color-primary: ${currentTheme.token.colorPrimary};
          }`}
          </style>
          <div
            style={{
              backgroundColor: currentTheme.token.colorBgLayout,
              color: currentTheme.token.colorText,
              borderRadius: '8px',
              boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
            }}
          >
            <AcquisitionTracer />
            <QuotaAlertModal />
            {children}
            {process.env.NODE_ENV === 'development' && <ProductSelector />}
            <div
              style={{
                position: 'fixed',
                top: '50%',
                right: 16,
                transform: 'translateY(-50%)',
                display: 'flex',
                flexDirection: 'column',
                gap: 8, // 按钮间距
                zIndex: 1000,
              }}
            >
              <Button
                type="primary"
                shape="circle"
                size="large"
                onClick={() => changeTheme(darkTheme)}
                title="Switch to Dark Theme"
              >
                🌙
              </Button>
              <Button
                type="primary"
                shape="circle"
                size="large"
                onClick={() => changeTheme(lightTheme)}
                title="Switch to Light Theme"
              >
                ☀️
              </Button>
            </div>
          </div>
        </IntlProvider>
      </ConfigProvider>
    </Provider>
  );
}

export default App;
