import { LogoutOutlined } from '@ant-design/icons';
import { history, RunTimeLayoutConfig } from '@umijs/max';
import { Dropdown } from 'antd';
import { handleRequestConfig } from '../config/Request';
import logo from '../public/logo.png';
import UnAccessPage from './components/403/403Page';
import { ROUTE_LOGIN } from './constants';
import { parseJwt } from './utils/jwtTokenUtils';
import { getToken, removeToken } from './utils/localStorageUtils';
// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState() {
  const token: string = getToken();
  const { pathname } = history.location;

  if (!token) {
    if (pathname !== ROUTE_LOGIN) {
      history.push(`${ROUTE_LOGIN}?redirect=${pathname}`);
    } else {
      history.push(ROUTE_LOGIN);
    }
    return {};
  }

  const parsed = parseJwt(token);
  if (!parsed) {
    removeToken();
    if (pathname !== ROUTE_LOGIN) {
      history.push(`${ROUTE_LOGIN}?redirect=${pathname}`);
    } else {
      history.push(ROUTE_LOGIN);
    }
    return {};
  }

  const { sub, exp } = parsed;
  const now = Math.floor(Date.now() / 1000);
  const oneHour = 60 * 60;

  if (exp - now < oneHour) {
    console.warn('Token expired or nearly expired, redirecting...');
    removeToken();
    if (pathname !== ROUTE_LOGIN) {
      history.push(`${ROUTE_LOGIN}?redirect=${pathname}`);
    } else {
      history.push(ROUTE_LOGIN);
    }
    return {};
  }

  return {
    currentUser: sub,
    exp,
  };
}

export const layout: RunTimeLayoutConfig = (initialState) => {
  console.log('initialState', initialState);

  return {
    logo: logo,
    fixedHeader: true,
    contentWidth: 'Fluid',
    navTheme: 'light',
    splitMenus: true,
    title: 'SGW',
    iconfontUrl: '//at.alicdn.com/t/c/font_1970684_76mmjhln75w.js',
    menu: {
      locale: false,
    },
    contentStyle: {
      padding: 0,
      margin: 0,
      paddingInline: 0,
    },
    avatarProps: {
      size: 'small',
      src: '/avatar.svg', // 👈 ở đây dùng icon thay vì src
      render: (_, dom) => {
        return (
          <Dropdown
            menu={{
              items: [
                {
                  key: 'logout',
                  icon: <LogoutOutlined />,
                  label: 'Đăng xuất',
                  onClick: () => {
                    removeToken();
                    history.push(ROUTE_LOGIN);
                  },
                },
              ],
            }}
          >
            {dom}
          </Dropdown>
        );
      },
    },
    layout: 'mix',
    logout: () => {
      removeToken();
      history.push(ROUTE_LOGIN);
    },
    // footerRender: () => <Footer />,
    onPageChange: () => {
      if (!initialState.initialState) {
        history.push(ROUTE_LOGIN);
      }
    },
    menuHeaderRender: undefined,
    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',
      },
    ],
    unAccessible: <UnAccessPage />,
    token: {
      pageContainer: {
        paddingInlinePageContainerContent: 0,
        paddingBlockPageContainerContent: 0,
      },
    },
  };
};

export const request = handleRequestConfig;
