import * as React from 'react';
import { useMatches, useLocation, Outlet, useNavigate } from 'react-router-dom';
import { Layout, Tour } from 'antd';
import type { TourProps } from 'antd';
import Header from './components/Header';
import Sidebar from './components/Sidebar';
import EntryModal from './components/EntryModal';
import { useLayoutStore } from './store';
import LocalStorage from '@/LocalStorage';
import './style.scss';
import loginStore from '../login/store';
const { Content } = Layout;

const LayoutApp: React.FC = () => {
  const ref1 = React.useRef(null);
  const ref2 = React.useRef(null);
  const ref3 = React.useRef(null);
  const ref4 = React.useRef(null);
  const ref5 = React.useRef(null);
  const navigate = useNavigate();
  
  const {
    routerMatchList,
    userName,
    collapsed,
    selectedKey,
    openKeys,
    onClickLogout,
    onChangeSelectedKey,
    onOpenChange,
    onClickCollapsed,
    setCollapsed,
    init,
    reset,
    onSetRouterMatchList,
    setUserName,
  } = useLayoutStore();

  const matches = useMatches();
  const location = useLocation();

  const [menuType, setMenuType] = React.useState<number>(1);
  const [entryModalOpen, setEntryModalOpen] = React.useState(false);
  const [openTour, setOpenTour] = React.useState(false);

  // 响应式初始化：移动端默认收起 Sidebar
  React.useEffect(() => {
    const checkMobile = () => {
      if (window.innerWidth <= 768) {
        setCollapsed(true);  // 移动端默认收起
      } else {
        setCollapsed(false);  // 桌面端默认展开
      }
    };
    
    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  React.useEffect(() => {
    const flag = LocalStorage.getMenuType();
    if (flag === 0) {
      setEntryModalOpen(true);
    } else {
      setMenuType(flag);
    }
    
    // 初始化用户名
    const userInfo = LocalStorage.getUserInfo();
    if (userInfo && userInfo.name) {
      setUserName(userInfo.name);
    }
  }, []);

  React.useEffect(() => {
    const path = location.pathname;
    // 应用导览
    if(path === '/appCenter/questionAnswer' && !localStorage.getItem('appTour')){
        setTimeout(()=>{
          setOpenTour(true);
        },800)
    }
    // 知识库导览
    if(path === '/knowledge/knowledgeLib' && !localStorage.getItem('knowledgeTour')){
        setTimeout(()=>{
          setOpenTour(true);
        },800)
    }
  }, [location.pathname]);
  
  const [tourOpen, setTourOpen] = React.useState(false);

  // 根据当前路由动态生成步骤
  const steps: TourProps['steps'] = React.useMemo(() => {
    const path = location.pathname;

    // 知识库页面导览步骤
    if (path === '/knowledge/knowledgeLib') {
      return [
        {
          title: '步骤 1.1 导航到知识库',
          description: '点击侧边栏的"知识库管理"菜单，进入"知识库"页面。',
          target: () => {
            const el = ref1.current;
            return el ? el : document.body;
          },
        },
        {
          title: '步骤 1.2 创建知识库',
          description: '点击右上角的"创建知识库"按钮，开始创建您的第一个知识库并上传知识文档。',
          target: () => {
            const el = ref2.current;
            return el? el : document.body;
          },
        },
        {
          title: '步骤 1.3 接下来还需要创建应用',
          description: '点击侧边栏的"应用中心"菜单，寻找"我创建的应用"页面，选择知识库，创建您的第一个 RAG 应用。',
          target: () => {
            const el = ref3.current;
            return el? el : document.body;
          },
        },
      ];
    }

    // 应用列表页面导览步骤
    if (path === '/appCenter/questionAnswer') {
      return [
        {
          title: '步骤 2.1 导航到我创建的应用',
          description: '点击侧边栏的"应用中心"菜单，将会自动展开"我创建的应用"页面。',
          target: () => {
            const el = ref5.current;
            return el? el : document.body;
          },
        },
        {
          title: '步骤 2.2 创建 RAG 应用',
          description: '点击右上角的"创建 RAG 应用"按钮，开始创建您的第一个应用，发布后即可在下方菜单中找到。',
          target: () => {
            const el = ref4.current;
            return el? el : document.body;
          },
        },
      ];
    }

    return [];
  }, [location.pathname]);
  
  const tourClose = () => {
    // 关闭引导后的一些操作
    const path = location.pathname;
    if (path === '/knowledge/knowledgeLib') {
      localStorage.setItem('knowledgeTour', 'true');
    } else if (path === '/appCenter/questionAnswer') {
      localStorage.setItem('appTour', 'true');
    }
    setOpenTour(false);
  }
  
  return (
    <Layout className='app-layout'>
      {/* Header */}
      <Header
        userName={userName}
        onClickLogout={onClickLogout}
      />

      {/* Sidebar */}
      <Sidebar />

      {/* 主体内容 */}
      <div className='main-container'>
        <Layout className='main-layout'>
          <Content className='main-content'>
            {
              location.pathname === '/404' &&
              <div style={{ width: '100%', height: 20 }}></div>
            }
            <div className='content-scroll-area'>
              <Outlet />
            </div>
          </Content>
        </Layout>
      </div>

      <Tour open={openTour} onClose={() => { tourClose();}} steps={steps} />
      {
        entryModalOpen &&
        <EntryModal
          open={entryModalOpen}
          onClickConfirm={(type) => {
            setEntryModalOpen(false);
            LocalStorage.setMenuType(type);
          }}
        />
      }
    </Layout>
  );
};

export default LayoutApp;
