/**
 * KRA - Basic Layout
 * Main application layout with sidebar and header
 */
import React, { useState, useEffect } from 'react';
import { Outlet, useLocation, useModel, history } from '@umijs/max';
import { ProLayout } from '@ant-design/pro-components';
import type { ProLayoutProps } from '@ant-design/pro-components';
import { Watermark } from 'antd';
import { Logo } from '@/components/Logo';
import { BottomInfo } from '@/components/BottomInfo';
import HeaderTools from './components/HeaderTools';
import Tabs from './components/Tabs';
import { useResponsive } from '@/hooks/useResponsive';
import defaultSettings from '../../config/defaultSettings';

const BasicLayout: React.FC = () => {
  const location = useLocation();
  const { initialState } = useModel('@@initialState');
  const { isMobile } = useResponsive();
  const [collapsed, setCollapsed] = useState(false);
  const [pathname, setPathname] = useState(location.pathname);

  const currentUser = initialState?.currentUser;
  const settings = initialState?.settings || defaultSettings;

  useEffect(() => {
    setPathname(location.pathname);
  }, [location.pathname]);

  const layoutProps: ProLayoutProps = {
    title: 'Kratos Admin',
    logo: '/logo.svg',
    layout: settings.layout || 'mix',
    navTheme: settings.navTheme || 'light',
    contentWidth: settings.contentWidth || 'Fluid',
    fixedHeader: settings.fixedHeader ?? true,
    fixSiderbar: settings.fixSiderbar ?? true,
    colorPrimary: settings.colorPrimary || '#1890ff',
    splitMenus: settings.splitMenus ?? false,
    collapsed,
    onCollapse: setCollapsed,
    location: { pathname },
    menu: {
      locale: false,
      request: async () => {
        // Return menu from initialState
        return initialState?.menus || [];
      },
    },
    menuItemRender: (item, dom) => (
      <div onClick={() => {
        setPathname(item.path || '/');
        history.push(item.path || '/');
      }}>
        {dom}
      </div>
    ),
    headerTitleRender: (logo, title) => (
      <Logo collapsed={collapsed} showTitle={!collapsed} />
    ),
    actionsRender: () => [
      <HeaderTools key="tools" />,
    ],
    footerRender: () => <BottomInfo />,
    menuFooterRender: (props) => {
      if (props?.collapsed) return undefined;
      return (
        <div style={{ textAlign: 'center', paddingBlockStart: 12 }}>
          <div>© {new Date().getFullYear()} KRA</div>
        </div>
      );
    },
  };

  return (
    <Watermark
      content={settings.showWatermark ? currentUser?.nickName : undefined}
      font={{ color: 'rgba(0, 0, 0, 0.15)' }}
      gap={[180, 150]}
      zIndex={9999}
    >
      <ProLayout {...layoutProps}>
        {settings.showTabs && <Tabs />}
        <Outlet />
      </ProLayout>
    </Watermark>
  );
};

export default BasicLayout;
