import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { SettingDrawer } from '@ant-design/pro-components';
import type { RequestConfig, RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import React from 'react';
import {
  AvatarDropdown,
  AvatarName,
  Footer,
  SelectLang,
} from '@/components';
import { ConnectButton } from '@/components/Web3/ConnectButton';
import { NetworkSwitch } from '@/components/Web3/NetworkSwitch';
import { getCurrentUser } from '@/services/auth/api';
import {
  clearTokens,
  getUserInfo,
  isLoggedIn,
} from '@/services/auth/tokenManager';
import defaultSettings from '../config/defaultSettings';
import { errorConfig } from './requestErrorConfig';
import '@ant-design/v5-patch-for-react-19';
import { WagmiProvider } from 'wagmi';
import { QueryClientProvider } from '@tanstack/react-query';
import { config, queryClient } from '@/config/wagmi';
import { TransactionProvider } from '@/context/TransactionContext';
import { ToastProvider } from '@/components/Toast';
import { useContractRegistry } from '@/hooks/useContractRegistry';

const isDev = process.env.NODE_ENV === 'development' || process.env.CI;
const loginPath = '/user/login';

// API 基础地址
const AUTH_BASE_URL = process.env.Auth_URL || '';

/**
 * @see https://umijs.org/docs/api/runtime-config#getinitialstate
 */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchUserInfo = async () => {
    // 检查是否已登录（refresh token 过期则彻底清除）
    if (!isLoggedIn()) {
      clearTokens();
      return undefined;
    }

    try {
      // 优先从 API 获取最新用户信息
      const response = await getCurrentUser();
      if (response.success && response.data) {
        // API 返回的 data 直接是用户对象
        const user = response.data;
        return {
          name: user.username,
          avatar: user.profile?.avatar || '',
          userid: user.userId || user.userID, // 使用数字 ID
          userId: user.userId || user.userID, // 兼容 userID 和 userId
          username: user.username,
          email: user.email,
          access: user.roles?.includes('admin') ? 'admin' : 'user',
          roles: user.roles || [],
        } as API.CurrentUser;
      }
    } catch (error) {
      // API 请求异常，继续尝试使用缓存
    }

    // API 失败或返回空数据时，尝试使用本地缓存的用户信息
    const cachedUser = getUserInfo();
    if (cachedUser) {
      return {
        name: cachedUser.username,
        avatar: cachedUser.profile?.avatar || '',
        userid: cachedUser.userId || cachedUser.userID, // 兼容 userID 和 userId
        userId: cachedUser.userId || cachedUser.userID, // 兼容 userID 和 userId
        username: cachedUser.username,
        email: cachedUser.email,
        access: cachedUser.roles?.includes('admin') ? 'admin' : 'user',
        roles: cachedUser.roles || [],
      } as API.CurrentUser;
    }

    // 缓存也没有，清除 Token
    clearTokens();
    return undefined;
  };

  // 如果不是登录/注册页面，执行获取用户信息
  const { location } = history;
  if (
    ![
      loginPath,
      '/user/register',
      '/user/register-result',
      '/user/forgot-password',
    ].includes(location.pathname)
  ) {
    const currentUser = await fetchUserInfo();
    if (!currentUser) {
      history.push(loginPath);
    }
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings as Partial<LayoutSettings>,
    };
  }

  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({
  initialState,
  setInitialState,
}) => {
  return {
    actionsRender: () => [
      <NetworkSwitch key="NetworkSwitch" />,
      <ConnectButton key="ConnectButton" />,
      <SelectLang key="SelectLang" />,
    ],
    avatarProps: {
      src: initialState?.currentUser?.avatar,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return <AvatarDropdown>{avatarChildren}</AvatarDropdown>;
      },
    },
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (
        !initialState?.currentUser &&
        ![
          loginPath,
          '/user/register',
          '/user/register-result',
          '/user/forgot-password',
        ].includes(location.pathname)
      ) {
        history.push(loginPath);
      }
    },
    bgLayoutImgList: [
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/D2LWSqNny4sAAAAAAAAAAAAAFl94AQBr',
        left: 85,
        bottom: 100,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/C2TWRpJpiC0AAAAAAAAAAAAAFl94AQBr',
        bottom: -68,
        right: -45,
        height: '303px',
      },
      {
        src: 'https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/F6vSTbj8KpYAAAAAAAAAAAAAFl94AQBr',
        bottom: 0,
        left: 0,
        width: '331px',
      },
    ],
    links: [],
    menuHeaderRender: undefined,
    childrenRender: (children) => {
      return (
        <>
          {children}
          {isDev && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * @doc https://umijs.org/docs/max/request#配置
 */
export const request: RequestConfig = {
  baseURL: AUTH_BASE_URL,
  ...errorConfig,
};

/**
 * @name rootContainer 配置，用于包裹整个应用
 * @doc https://umijs.org/docs/api/runtime-config#rootcontainer
 */
function ContractRegistryInit({ children }: { children: React.ReactNode }) {
  useContractRegistry();
  return <>{children}</>;
}

export function rootContainer(container: React.ReactNode) {
  return (
    <WagmiProvider config={config}>
      <QueryClientProvider client={queryClient}>
        <ContractRegistryInit>
          <ToastProvider>
            <TransactionProvider>
              {container}
            </TransactionProvider>
          </ToastProvider>
        </ContractRegistryInit>
      </QueryClientProvider>
    </WagmiProvider>
  );
}
