import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { useEffect, useMemo, useState } from 'react';

import type { QuickActionType } from '../data/mockData';
import { QuickActionModal } from '../components/modals/QuickActionModal';
import { LoginModal } from '../components/modals/LoginModal';
import { Sidebar, type SectionKey } from '../components/layout/Sidebar';
import { TopBar } from '../components/layout/TopBar';

export interface MainLayoutContext {
  search: string;
  setSearch: (value: string) => void;
}

const sectionToRoute: Record<SectionKey, string> = {
  home: '/home',
  exam: '/exam',
  booking: '/booking',
  support: '/support',
};

const routeToSection = Object.entries(sectionToRoute).reduce<Record<string, SectionKey>>(
  (acc, [section, route]) => {
    acc[route] = section as SectionKey;
    return acc;
  },
  {},
);

interface LoginInfo {
  userId: string;
  userName: string;
  accessToken: string;
  refreshToken: string;
  roles: string;
  username: string;
}

export const MainLayout = () => {
  const [search, setSearch] = useState('');
  const [quickAction, setQuickAction] = useState<QuickActionType>('none');
  const [noteText, setNoteText] = useState('');
  const [loginModalOpen, setLoginModalOpen] = useState(false);
  const [operatorName, setOperatorName] = useState<string>('');

  const navigate = useNavigate();
  const location = useLocation();

  const activeSection: SectionKey = useMemo(() => {
    const matched = Object.entries(routeToSection).find(([path]) => location.pathname.startsWith(path));
    return (matched?.[1] || 'home') as SectionKey;
  }, [location.pathname]);

  const handleNavigate = (section: SectionKey) => {
    navigate(sectionToRoute[section]);
  };

  const handleLoginSuccess = (info: LoginInfo) => {
    const displayName = info.userName || info.username || '操作员';
    setOperatorName(displayName);
    // 存储操作员信息与 token
    localStorage.setItem('operatorId', info.userId || '');
    localStorage.setItem('operatorName', displayName);
    localStorage.setItem('operatorUsername', info.username || '');
    localStorage.setItem('accessToken', info.accessToken || '');
    localStorage.setItem('refreshToken', info.refreshToken || '');
    // 触发自定义事件，通知其他组件更新状态
    window.dispatchEvent(new Event('localStorageChange'));
  };

  // 初始化时检查是否有已登录的操作员
  useEffect(() => {
    const savedName = localStorage.getItem('operatorName');
    if (savedName) {
      setOperatorName(savedName);
    }
  }, []);

  // 监听 localStorage 变化，更新操作员名称
  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === 'operatorName') {
        setOperatorName(e.newValue || '');
      }
    };

    // 监听 storage 事件（跨标签页）
    window.addEventListener('storage', handleStorageChange);

    // 监听自定义事件（同标签页内）
    const handleCustomStorageChange = () => {
      const savedName = localStorage.getItem('operatorName');
      if (savedName) {
        setOperatorName(savedName);
      }
    };
    window.addEventListener('localStorageChange', handleCustomStorageChange);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
      window.removeEventListener('localStorageChange', handleCustomStorageChange);
    };
  }, []);

  // 当登录弹窗关闭时，重新读取操作员名称
  useEffect(() => {
    if (!loginModalOpen) {
      const savedName = localStorage.getItem('operatorName');
      if (savedName) {
        setOperatorName(savedName);
      }
    }
  }, [loginModalOpen]);

  // 检查 URL 参数，如果包含 login=true，则打开登录弹窗
  useEffect(() => {
    const searchParams = new URLSearchParams(location.search);
    if (searchParams.get('login') === 'true') {
      setLoginModalOpen(true);
      // 清除 URL 参数，避免刷新后再次打开
      navigate(location.pathname, { replace: true });
    }
  }, [location.search, location.pathname, navigate]);

  return (
    <div className='h-screen bg-gray-50 text-gray-900 grid grid-cols-[240px_1fr] overflow-hidden'>
      <Sidebar active={activeSection} onNavigate={handleNavigate} onQuickAction={setQuickAction} />

      <div className='flex flex-col h-screen overflow-hidden'>
        <TopBar
          search={search}
          onSearch={setSearch}
          enableSearch={activeSection === 'exam'}
          operatorName={operatorName}
          onLoginClick={() => setLoginModalOpen(true)}
        />
        <main className='p-6  flex-1 overflow-auto'>
          <Outlet context={{ search, setSearch }} />
        </main>
      </div>

      {loginModalOpen && (
        <LoginModal
          onClose={() => setLoginModalOpen(false)}
          onLoginSuccess={handleLoginSuccess}
        />
      )}

      {quickAction !== 'none' && (
        <QuickActionModal
          action={quickAction}
          noteText={noteText}
          onNoteChange={setNoteText}
          onClose={() => setQuickAction('none')}
        />
      )}
    </div>
  );
};


