import { lazy, Suspense, useEffect } from 'react'
import { createRouter, createRootRoute, createRoute, Outlet, useNavigate, useRouterState } from '@tanstack/react-router'
import { WorkspacePage } from '@/features/workspace/WorkspacePage'
import { ImportPage } from '@/features/import/ImportPage'
import { LibraryPage } from '@/features/library/LibraryPage'
import { SettingsPage } from '@/features/settings/SettingsPage'
import { LoginPage } from '@/features/login/LoginPage'
import { useAuth } from '@/auth/AuthContext'
import { Loader2 } from 'lucide-react'

const ReportPage = lazy(() =>
  import('@/features/report/ReportPage').then((m) => ({ default: m.ReportPage }))
)

function ReportPageWithSuspense() {
  return (
    <Suspense fallback={
      <div className="min-h-screen flex flex-col items-center justify-center gap-3 bg-slate-50">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
        <p className="text-sm text-slate-400">Cargando reporte…</p>
      </div>
    }>
      <ReportPage />
    </Suspense>
  )
}

function RootComponent() {
  const { user, loading } = useAuth()
  const navigate = useNavigate()
  const pathname = useRouterState({ select: (s) => s.location.pathname })

  useEffect(() => {
    if (loading) return
    if (!user && pathname !== '/login') {
      void navigate({ to: '/login' })
    } else if (user && pathname === '/login') {
      void navigate({ to: '/' })
    }
  }, [user, loading, pathname, navigate])

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin" style={{ color: '#F59845' }} />
      </div>
    )
  }

  if (!user && pathname !== '/login') return null

  return <Outlet />
}

const rootRoute = createRootRoute({ component: RootComponent })

const loginRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/login',
  component: LoginPage,
})

const indexRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/',
  component: LibraryPage,
})

const importRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/import',
  component: ImportPage,
})

const workspaceRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/workspace/$processId',
  component: WorkspacePage,
})

const reportRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/report/$processId',
  component: ReportPageWithSuspense,
})

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

const routeTree = rootRoute.addChildren([
  loginRoute,
  indexRoute,
  importRoute,
  workspaceRoute,
  reportRoute,
  settingsRoute,
])

export const router = createRouter({ routeTree })

declare module '@tanstack/react-router' {
  interface Register { router: typeof router }
}
