/* eslint-disable import/no-extraneous-dependencies */
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import { createBlockletPlugin } from 'vite-plugin-blocklet';
import svgr from 'vite-plugin-svgr';
import tsconfigPaths from 'vite-tsconfig-paths';
import { visualizer } from 'rollup-plugin-visualizer';
import path from 'path';
import { codeInspectorPlugin } from 'code-inspector-plugin';

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const isProduction = mode === 'production';
  const isDevelopment = mode === 'development';
  const alias: Record<string, string> = {};

  const arcblockUxBasePath = process.env.ARCBLOCK_UX_BASE_PATH;
  const exclude: string[] = [];
  if (arcblockUxBasePath) {
    alias['@arcblock/ux'] = `${arcblockUxBasePath}/packages/ux`;
    alias['@arcblock/ux/lib'] = `${arcblockUxBasePath}/packages/ux/src`;
    alias['@blocklet/ui-react'] = `${arcblockUxBasePath}/packages/blocklet-ui-react`;
    alias['@blocklet/ui-react/lib'] = `${arcblockUxBasePath}/packages/blocklet-ui-react/src`;
    alias['@arcblock/did-connect-react'] = `${arcblockUxBasePath}/packages/did-connect`;
    alias['@arcblock/did-connect-react/lib'] = `${arcblockUxBasePath}/packages/did-connect/src`;
    exclude.push(
      '@arcblock/ux',
      '@arcblock/ux/lib',
      '@blocklet/ui-react',
      '@blocklet/ui-react/lib',
      '@arcblock/did-connect-react',
      '@arcblock/did-connect-react/lib'
    );
  }

  if (isDevelopment) {
    alias['@blocklet/payment-react'] = path.resolve(__dirname, '../../packages/react/src');
    alias['@blocklet/payment-react-headless'] = path.resolve(__dirname, '../../packages/payment-react-headless/src');
    alias['@blocklet/payment-js'] = path.resolve(__dirname, '../../packages/client/src');
    exclude.push('@blocklet/payment-react', '@blocklet/payment-react-headless', '@blocklet/payment-js');
  }

  if (isProduction) {
    // mui-datatable
    alias['lodash.assign'] = 'lodash/assign';
    alias['lodash.clonedeep'] = 'lodash/cloneDeep';
    alias['lodash.isequal'] = 'lodash/isEqual';
    alias['lodash.merge'] = 'lodash/merge';
    alias['lodash.find'] = 'lodash/find';
  }

  return {
    plugins: [
      tsconfigPaths(),
      react({ babel: { plugins: isProduction ? [['lodash']] : [] } }),
      createBlockletPlugin({
        disableDynamicAssetHost: false,
        chunkSizeLimit: 3500,
      }),
      svgr(),
      process.env.ANALYZE && visualizer({ open: true, gzipSize: true, brotliSize: true }),
      // @note: 如果开发期间，文件隔离模式报错了，那么可以关闭server的文件隔离模式
      isProduction &&
        codeInspectorPlugin({
          bundler: 'vite',
        }),
    ].filter(Boolean),

    build: {
      cssCodeSplit: false,
      minify: 'terser',
      modulePreload: false,
      terserOptions: { compress: { drop_debugger: true, pure_funcs: ['assert', 'debug'] } } as any,
      reportCompressedSize: false,
      chunkSizeWarningLimit: 1000,
      commonjsOptions: { include: [/node_modules/], transformMixedEsModules: true },
      rollupOptions: {
        external: [],
        output: {
          manualChunks: {
            'vendor-react': ['react', 'react-dom', 'react-router-dom'],
            'vendor-mui': [
              '@mui/material',
              '@mui/icons-material',
              '@mui/system',
              '@mui/lab',
              // '@mui/material-nextjs',
              '@mui/styled-engine',
              // '@mui/styled-engine-sc',
              '@mui/utils',
              // '@mui/x-data-grid',
              // '@mui/x-data-grid-pro',
              // '@mui/x-data-grid-premium',
              // '@mui/x-date-pickers',
              // '@mui/x-date-pickers-pro',
              // '@mui/x-charts',
              // '@mui/x-tree-view',
              // '@mui/x-tree-view-pro',
            ],
            moment: ['moment', 'moment-timezone'],
            utils: ['dayjs', 'numbro', 'bn.js'],
            hooks: ['ahooks', 'use-bus'],
            'vendor-arcblock': ['@arcblock/did-connect-react', '@arcblock/ux'],
            'vendor-blocklet': ['@blocklet/ui-react'],
          },
        },
      },
    },
    optimizeDeps: {
      include: ['react', 'react-dom', 'react/jsx-runtime'],
      esbuildOptions: { mainFields: ['module', 'main'], resolveExtensions: ['.ts', '.tsx', '.js', '.jsx'] },
      exclude,
    },
    resolve: {
      alias,
      dedupe: [
        //
        '@blocklet/ui-react',
        '@arcblock/ux',
        '@arcblock/did-connect-react',
        '@mui/material',
        // '@mui/utils',
        '@mui/icons-material',
        'react',
        'react-dom',
        'lodash',
        'bn.js',
      ],
    },
  };
});
