import { createRootRoute, createRoute, Outlet, redirect } from '@tanstack/react-router'
import Layout from '@/components/Layout'
import { lazyPage } from '@/lib/lazy-page'
import { getAuthStatus } from '@/lib/auth'

// 轻量入口页直接加载，其余路由懒加载以降低主包
import Login from '@/pages/Login'
import Install from '@/pages/Install'
import NotFound from '@/pages/NotFound'
import { ErrorPage } from '@/pages/ErrorPage'

const Dashboard = lazyPage(() => import('@/pages/Dashboard'))
const Tasks = lazyPage(() => import('@/pages/Tasks'))
const Editor = lazyPage(() => import('@/pages/Editor'))
const Environments = lazyPage(() => import('@/pages/Environments'))
const Languages = lazyPage(() => import('@/pages/Languages'))
const Dependencies = lazyPage(() => import('@/pages/Dependencies'))
const Agents = lazyPage(() => import('@/pages/Agents'))
const History = lazyPage(() => import('@/pages/History'))
const MessageLogs = lazyPage(() => import('@/pages/MessageLogs'))
const Terminal = lazyPage(() => import('@/pages/Terminal'))
const Notify = lazyPage(() => import('@/pages/Notify'))
const Monitor = lazyPage(() => import('@/pages/Monitor'))
const Interconnect = lazyPage(() => import('@/pages/Interconnect'))
const Settings = lazyPage(() => import('@/pages/Settings'))

const rootRoute = createRootRoute({
  component: Outlet,
  errorComponent: ErrorPage,
  notFoundComponent: NotFound,
})

const loginRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/login',
  component: Login,
  beforeLoad: async () => {
    const isAuthenticated = await getAuthStatus(true)
    if (isAuthenticated) {
      throw redirect({ to: '/' })
    }
  },
})

const installRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/install',
  component: Install,
})

// pathless layout，避免与 dashboard 的 path `/` 产生重复路由 id
const layoutRoute = createRoute({
  getParentRoute: () => rootRoute,
  id: 'app',
  component: Layout,
  beforeLoad: async () => {
    const isAuthenticated = await getAuthStatus()
    if (!isAuthenticated) {
      throw redirect({ to: '/login' })
    }
  },
})

const dashboardRoute = createRoute({
  getParentRoute: () => layoutRoute,
  path: '/',
  component: Dashboard,
})

const tasksRoute = createRoute({
  getParentRoute: () => layoutRoute,
  path: '/tasks',
  component: Tasks,
  validateSearch: (search: Record<string, unknown>) => ({
    agent_id: typeof search.agent_id === 'string' ? search.agent_id : undefined,
    type: typeof search.type === 'string' ? search.type : undefined,
    tags: typeof search.tags === 'string' ? search.tags : undefined,
  }),
})

const agentsRoute = createRoute({
  getParentRoute: () => layoutRoute,
  path: '/agents',
  component: Agents,
})

const editorRoute = createRoute({
  getParentRoute: () => layoutRoute,
  path: '/editor',
  component: Editor,
})

const historyRoute = createRoute({
  getParentRoute: () => layoutRoute,
  path: '/history',
  component: History,
  validateSearch: (search: Record<string, unknown>) => ({
    status: typeof search.status === 'string' ? search.status : undefined,
    task_name: typeof search.task_name === 'string' ? search.task_name : undefined,
  }),
})

const environmentsRoute = createRoute({
  getParentRoute: () => layoutRoute,
  path: '/environments',
  component: Environments,
})

const languagesRoute = createRoute({
  getParentRoute: () => layoutRoute,
  path: '/languages',
  component: Languages,
})

const dependenciesRoute = createRoute({
  getParentRoute: () => layoutRoute,
  path: '/dependencies',
  component: Dependencies,
  validateSearch: (search: Record<string, unknown>) => ({
    language: typeof search.language === 'string' ? search.language : undefined,
    version: typeof search.version === 'string' ? search.version : undefined,
  }),
})

const terminalRoute = createRoute({
  getParentRoute: () => layoutRoute,
  path: '/terminal',
  component: Terminal,
})

const notifyRoute = createRoute({
  getParentRoute: () => layoutRoute,
  path: '/notify',
  component: Notify,
})

const logsRoute = createRoute({
  getParentRoute: () => layoutRoute,
  path: '/logs',
  component: MessageLogs,
})

const monitorRoute = createRoute({
  getParentRoute: () => layoutRoute,
  path: '/monitor',
  component: Monitor,
})

const interconnectRoute = createRoute({
  getParentRoute: () => layoutRoute,
  path: '/interconnect',
  component: Interconnect,
})

const settingsRoute = createRoute({
  getParentRoute: () => layoutRoute,
  path: '/settings',
  component: Settings,
})

const notFoundRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/404',
  component: NotFound,
})

const catchAllRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '$',
  beforeLoad: () => {
    throw redirect({ to: '/404' })
  },
})

export const routeTree = rootRoute.addChildren([
  loginRoute,
  installRoute,
  notFoundRoute,
  catchAllRoute,
  layoutRoute.addChildren([
    dashboardRoute,
    tasksRoute,
    agentsRoute,
    editorRoute,
    historyRoute,
    environmentsRoute,
    languagesRoute,
    dependenciesRoute,
    terminalRoute,
    notifyRoute,
    logsRoute,
    monitorRoute,
    interconnectRoute,
    settingsRoute,
  ]),
])
