import type { ReactElement } from 'react';
import { createBrowserRouter, Navigate, Outlet, type RouteObject } from 'react-router-dom';
import { LoginPage } from '@/spa/pages/login';
import { RegisterPage } from '@/spa/pages/register';
import { SsoCallbackPage } from '@/spa/pages/sso-callback';
import { ChatPage } from '@/spa/pages/chat';
import { ChatRouteErrorBoundary } from '@/spa/pages/chat-error-boundary';
import { ProjectDetailPage } from '@/spa/pages/project-detail';
import { ProjectsPage } from '@/spa/pages/projects';
import {
  ProjectDetailRouteErrorBoundary,
  ProjectsRouteErrorBoundary,
  TasksRouteErrorBoundary,
} from '@/spa/pages/resource-route-error-boundaries';
import { TasksPage } from '@/spa/pages/tasks';
import { AuthGuard, GuestGuard } from '@/spa/guards';
import { Placeholder } from '@/spa/placeholder';

function GuestLayout(): ReactElement {
  return (
    <div className="flex min-h-screen items-center justify-center bg-surface-bg px-4 py-8">
      <div className="w-full max-w-md rounded-xl border border-surface-border bg-surface-card p-8 shadow-lg">
        <Outlet />
      </div>
    </div>
  );
}

export const routes: RouteObject[] = [
  {
    element: <GuestGuard />,
    children: [
      {
        element: <GuestLayout />,
        children: [
          { path: '/login', element: <LoginPage /> },
          { path: '/register', element: <RegisterPage /> },
          { path: '/auth/provider/:provider', element: <SsoCallbackPage /> },
        ],
      },
    ],
  },
  {
    element: <AuthGuard />,
    children: [
      { path: '/', element: <Navigate to="/chat" replace /> },
      { path: '/chat', element: <ChatPage />, errorElement: <ChatRouteErrorBoundary /> },
      {
        path: '/projects',
        element: <ProjectsPage />,
        errorElement: <ProjectsRouteErrorBoundary />,
      },
      {
        path: '/projects/:id',
        element: <ProjectDetailPage />,
        errorElement: <ProjectDetailRouteErrorBoundary />,
      },
      { path: '/tasks', element: <TasksPage />, errorElement: <TasksRouteErrorBoundary /> },
      { path: '/settings', element: <Placeholder title="Settings" /> },
      { path: '/admin', element: <Placeholder title="Admin" /> },
    ],
  },
];

export function createAppRouter(): ReturnType<typeof createBrowserRouter> {
  return createBrowserRouter(routes);
}
