import { useEffect } from 'react';
import { Navigate, Route, Routes, useLocation, useNavigate } from 'react-router-dom';
import MainLayout from '../components/layout/MainLayout';
import HomePage from '../pages/Home';
import LoginPage from '../pages/Login';
import AgentsPage from '../pages/agents';
import SkillsPage from '../pages/Skills';
import CronPage from '../pages/Cron';
import ScriptsPage from '../pages/Scripts';
import SettingPage from '../pages/Setting';
import KnowledgePage from '../pages/Knowledge';
import { DEFAULT_PATH } from './routes';
import { RedirectAuthenticated, RequireAuth, isAuthenticated } from './auth';
import { onAuthLogout } from './auth-session';

function AuthLogoutRedirector() {
  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    return onAuthLogout(({ from }) => {
      const currentPath = location.pathname === '/login' ? undefined : location.pathname;
      navigate('/login', {
        replace: true,
        state: { from: from ?? currentPath },
      });
    });
  }, [location.pathname, navigate]);

  return null;
}

export function AppRouter() {
  const initialPath = isAuthenticated() ? DEFAULT_PATH : '/login';

  return (
    <>
      <AuthLogoutRedirector />
      <Routes>
        <Route path="/" element={<Navigate to={initialPath} replace />} />
        <Route element={<RedirectAuthenticated />}>
          <Route path="/login" element={<LoginPage />} />
        </Route>

        <Route element={<RequireAuth />}>
          <Route element={<MainLayout />}>
            <Route path="/home" element={<HomePage />} />
            <Route path="/agents" element={<AgentsPage />} />
            <Route path="/skills" element={<SkillsPage />} />
            <Route path="/cron" element={<CronPage />} />
            <Route path="/scripts" element={<ScriptsPage />} />
            <Route path="/setting" element={<SettingPage />} />
            <Route path="/knowledge" element={<KnowledgePage />} />
          </Route>
        </Route>

        <Route path="*" element={<Navigate to={initialPath} replace />} />
      </Routes>
    </>
  );
}
