import { BrowserRouter, Routes, Route, Link, useLocation, useNavigate, Navigate } from 'react-router-dom'
import { QueryClient, QueryClientProvider, QueryCache, MutationCache } from '@tanstack/react-query'
import { ErrorBoundary } from './components/ErrorBoundary'
import { ShortcutHelpBanner, SHOW_SHORTCUT_HELP_EVENT } from './components/ShortcutHelpBanner'
import { showApiError } from './lib/toast'
import { useKeyboardShortcuts } from './hooks/useKeyboardShortcuts'
import { requestFocusSearch } from './hooks/useFocusSearch'
import Dashboard from './pages/Dashboard'
import MealDetail from './pages/MealDetail'
import Pantry from './pages/Pantry'
import Recipes from './pages/Recipes'
import Recommended from './pages/Recommended'
import RecipeDetail from './pages/RecipeDetail'
import ShoppingList from './pages/ShoppingList'
import NotFound from './pages/NotFound'

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: 1,
      refetchOnWindowFocus: false,
    },
  },
  queryCache: new QueryCache({
    onError: (error) => {
      showApiError(error, 'Failed to load data')
    },
  }),
  mutationCache: new MutationCache({
    onError: (error) => {
      showApiError(error)
    },
  }),
})

function Navigation() {
  const location = useLocation()
  const path = location.pathname
  const isActive = (prefix: string) => path === prefix || path.startsWith(prefix + '/')

  const linkClass = (prefix: string) =>
    `inline-flex items-center px-2 sm:px-3 py-2 text-sm font-medium rounded-lg transition-colors whitespace-nowrap ${
      isActive(prefix)
        ? 'text-primary-700 bg-primary-50'
        : 'text-surface-600 hover:bg-surface-100'
    }`

  return (
    <nav className="bg-white border-b border-surface-200 sticky top-0 z-50" aria-label="Primary">
      <div className="max-w-7xl mx-auto px-3 sm:px-6 lg:px-8">
        <div className="flex items-center gap-1 min-h-14 py-2">
          <Link to="/" className={linkClass('/')} aria-current={isActive('/') ? 'page' : undefined}>MealPlanner</Link>
          <Link to="/recipes" className={linkClass('/recipes')} aria-current={isActive('/recipes') ? 'page' : undefined}>Recipes</Link>
          <Link to="/pantry" className={linkClass('/pantry')} aria-current={isActive('/pantry') ? 'page' : undefined}>Pantry</Link>
          <Link to="/shopping-list" className={linkClass('/shopping-list')} aria-current={isActive('/shopping-list') ? 'page' : undefined}>Shopping List</Link>
        </div>
      </div>
    </nav>
  )
}

function GlobalShortcuts() {
  const navigate = useNavigate()
  useKeyboardShortcuts({
    'g d': () => navigate('/'),
    'g r': () => navigate('/recipes'),
    'g p': () => navigate('/pantry'),
    'g s': () => navigate('/shopping-list'),
    '/': () => requestFocusSearch(),
    '?': () => window.dispatchEvent(new CustomEvent(SHOW_SHORTCUT_HELP_EVENT)),
  })
  return null
}

function App() {
  return (
    <ErrorBoundary>
      <QueryClientProvider client={queryClient}>
        <BrowserRouter>
          <GlobalShortcuts />
          <div className="min-h-screen bg-surface-50">
            <Navigation />
            <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8" id="main-content">
              <Routes>
                <Route path="/" element={<Dashboard />} />
                <Route path="/meals/:id" element={<MealDetail />} />
                <Route path="/recipes" element={<Recipes />} />
                <Route path="/recipes/recommended" element={<Recommended />} />
                <Route path="/recommended" element={<Navigate to="/recipes/recommended" replace />} />
                <Route path="/recipes/:id" element={<RecipeDetail />} />
                <Route path="/pantry" element={<Pantry />} />
                <Route path="/shopping-list" element={<ShoppingList />} />
                <Route path="*" element={<NotFound />} />
              </Routes>
            </main>
            <ShortcutHelpBanner />
          </div>
        </BrowserRouter>
      </QueryClientProvider>
    </ErrorBoundary>
  )
}

export default App
