// entrypoints/popup/App.tsx
import { useState, useEffect } from 'react';
import { HashRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { Link, useNavigate } from 'react-router-dom';
import { Button, Dropdown, Menu } from '@alifd/next';
import './App.css';
import '../../assets/tailwind.css'
import '@alifd/next/dist/next.css';
import '@alifd/next/dist/next.min.css';
import Login from './pages/Login'
import DesignPic from './pages/DesignPic';
import { useLoading } from '@/components/LoadingContext';
import AutoOptions from './pages/AutoOptions';
import IconCom from '@/components/IconCom';

// 创建一个保护路由组件
function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const isLoggedIn = localStorage.getItem('isLoggedIn');
  return isLoggedIn ? <>{children}</> : <Navigate to="/login" replace />;
}

// 创建带登出功能的导航组件
function Navigation({ onLogout, userinfo }: { onLogout: () => void, userinfo: any }) {
  const navigate = useNavigate();

  const handleLogout = () => {
    onLogout();
    navigate('/login');
  };

  const menu = (
    <Menu>
      <Menu.Item>
        <Link to="/" className="text-blue-500 hover:underline">定制信息</Link>
      </Menu.Item>
      <Menu.Item>
        <Link to="/autoOptions" className="text-blue-500 hover:underline">自动发送</Link>
      </Menu.Item>
    </Menu>
  );

  return (
    <div className="flex gap-4 items-center justify-between">
      <div className='font-bold'>{userinfo && userinfo.nickname ? <div>
        <span className='mr-4'>等级: {userinfo.version_custom_name}</span>
        <span>账户: {userinfo.nickname}</span>
      </div> : <>未获取到用户信息</>}</div>
      <nav className="flex gap-4 items-center">
        {/* <div>
          <Dropdown
            trigger={<Button style={{ width: 30, padding: 3 }}><IconCom type='list' /></Button>}
            onVisibleChange={console.log}
            triggerType={['hover']}
            afterOpen={() => console.log('after open')}
          >
            {menu}
          </Dropdown>
        </div> */}
        <Button
          type="normal" warning
          onClick={handleLogout}
        >
          退出登录
        </Button>
      </nav>
    </div>
  );
}

function App() {
  const [count, setCount] = useState(0);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [userinfo, setUserinfo] = useState<any>(null);
  const { showLoading, hideLoading } = useLoading();

  // 检查登录状态
  useEffect(() => {
    const loggedIn = localStorage.getItem('isLoggedIn') === 'true';
    setIsLoggedIn(loggedIn);
  }, []);

  useEffect(() => {
    // 获取用户信息
    if (isLoggedIn) {
      if (localStorage.getItem('userinfo')) {
        let userinfoStr = localStorage.getItem('userinfo');
        try {
          // 尝试解析用户信息
          const parsedUserinfo = userinfoStr ? JSON.parse(userinfoStr) : null;
          setUserinfo(parsedUserinfo);
        } catch (e) {
          // 如果解析失败，可能是字符串格式
          setUserinfo({ nickname: userinfoStr });
        }
      }
    }
  }, [isLoggedIn])

  // 处理登出逻辑
  const handleLogout = () => {
    showLoading("退出登录中...")
    setTimeout(() => {
      hideLoading()
      localStorage.removeItem('isLoggedIn');
      localStorage.removeItem('access_token');
      localStorage.removeItem('userinfo');
      setIsLoggedIn(false);
    }, 500)
  };

  return (
    <Router>
      {/* 只在登录后显示导航栏 */}
      {isLoggedIn && <Navigation onLogout={handleLogout} userinfo={userinfo} />}

      <Routes>
        <Route path="/login" element={<Login setIsLoggedIn={setIsLoggedIn} />} />
        <Route path="/" element={
          <ProtectedRoute>
            <DesignPic />
          </ProtectedRoute>
        } />
        <Route path="/autoOptions" element={
          <ProtectedRoute>
            <AutoOptions />
          </ProtectedRoute>
        } />
      </Routes>
    </Router>
  );
}

export default App;