import { useState, useCallback } from 'react'
import { createRootRoute, Link, Outlet } from '@tanstack/react-router'
import { AppLayout } from '../layouts/AppLayout'
import { ErrorBoundary } from '../components/ErrorBoundary'
import { Toaster } from '../components/ui/sonner'
import { Button } from '../components/ui/button'
import { CommandPalette } from '../components/CommandPalette'
import { ConnectionBanner } from '../components/ConnectionBanner'
import { BrowserTitleUpdater } from '../components/BrowserTitleUpdater'
import { useConnectionStatus } from '../hooks/useConnectionStatus'
import { useGlobalKeyboard } from '../hooks/useGlobalKeyboard'

function RootLayout() {
  const [commandPaletteOpen, setCommandPaletteOpen] = useState(false)
  const connectionState = useConnectionStatus()

  const openCommandPalette = useCallback(() => {
    setCommandPaletteOpen(true)
  }, [])

  useGlobalKeyboard({ onCommandK: openCommandPalette })

  return (
    <>
      <ConnectionBanner state={connectionState} />
      <AppLayout onOpenCommandPalette={openCommandPalette} connectionState={connectionState}>
        <ErrorBoundary>
          <Outlet />
        </ErrorBoundary>
      </AppLayout>
      <CommandPalette
        open={commandPaletteOpen}
        onClose={() => setCommandPaletteOpen(false)}
      />
      <BrowserTitleUpdater />
      <Toaster />
    </>
  )
}

export const Route = createRootRoute({
  component: RootLayout,
  notFoundComponent: () => (
    <div className="flex flex-col items-center justify-center gap-4 py-12">
      <h1 className="text-2xl font-bold">Page not found</h1>
      <p className="text-muted-foreground">The page you are looking for does not exist.</p>
      <Button variant="outline" asChild>
        <Link to="/initiatives">Back to Dashboard</Link>
      </Button>
    </div>
  ),
})
