import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useState, useEffect, useCallback } from 'react'
import { Layout } from '@/components/Layout'
import { DashboardPage } from '@/pages/DashboardPage'
import { TasksPage } from '@/pages/TasksPage'
import { TaskDetailPage } from '@/pages/TaskDetailPage'
import { StoreDetailPage } from '@/pages/StoreDetailPage'
import { MonthlyReviewPage } from '@/pages/MonthlyReviewPage'
import { IndicatorsPage } from '@/pages/IndicatorsPage'
import { RegionalPage } from '@/pages/RegionalPage'
import { StorePage } from '@/pages/StorePage'
import { SKUPage } from '@/pages/SKUPage'
import { CostPage } from '@/pages/CostPage'
import { CostAnalysisPage } from '@/pages/CostAnalysisPage'
import { StoreExpensePage } from '@/pages/StoreExpensePage'
import { PlatformPage } from '@/pages/PlatformPage'
import { MemberPage } from '@/pages/MemberPage'
import { RiskPage } from '@/pages/RiskPage'
import { TimePage } from '@/pages/TimePage'
import { DataQualityPage } from '@/pages/DataQualityPage'
import { OntologyPage } from '@/pages/OntologyPage'
import { SiteSelectionPage } from '@/pages/SiteSelectionPage'
import { SmartSchedulingPage } from '@/pages/SmartSchedulingPage'
import { SituationalAwarenessPage } from '@/pages/SituationalAwarenessPage'
import { BossPage } from '@/pages/BossPage'
import { RevenuePage } from '@/pages/RevenuePage'
import { BankPage } from '@/pages/BankPage'
import { LoginPage } from '@/pages/LoginPage'

const queryClient = new QueryClient({
  defaultOptions: {
    queries: { refetchOnWindowFocus: false, retry: 1 },
  },
})

export default function App() {
  const [user, setUser] = useState<any>(null)
  const [ready, setReady] = useState(false)

  useEffect(() => {
    const stored = localStorage.getItem('user')
    if (stored) setUser(JSON.parse(stored))
    setReady(true)
  }, [])

  const handleLogout = useCallback(() => {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    setUser(null)
  }, [])

  const handleLogin = useCallback((u: any) => {
    setUser(u)
  }, [])

  if (!ready) return null

  const token = localStorage.getItem('token')

  return (
    <QueryClientProvider client={queryClient}>
      <BrowserRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}>
        {!token ? (
          <Routes>
            <Route path="/login" element={<LoginPage onLogin={handleLogin} />} />
            <Route path="*" element={<Navigate to="/login" />} />
          </Routes>
        ) : (
          <Layout user={user} onLogout={handleLogout}>
            <Routes>
              <Route path="/" element={<DashboardPage />} />
              <Route path="/boss" element={<BossPage />} />
              <Route path="/revenue" element={<RevenuePage />} />
              <Route path="/bank" element={<BankPage />} />
              <Route path="/regional" element={<RegionalPage />} />
              <Route path="/store" element={<StorePage />} />
              <Route path="/tasks" element={<TasksPage />} />
              <Route path="/tasks/:id" element={<TaskDetailPage />} />
              <Route path="/stores/:code" element={<StoreDetailPage />} />
              <Route path="/monthly-review" element={<MonthlyReviewPage />} />
              <Route path="/sku" element={<SKUPage />} />
              <Route path="/cost" element={<CostPage />} />
              <Route path="/cost-analysis" element={<CostAnalysisPage />} />
              <Route path="/store-expense" element={<StoreExpensePage />} />
              <Route path="/platform" element={<PlatformPage />} />
              <Route path="/member" element={<MemberPage />} />
              <Route path="/risk" element={<RiskPage />} />
              <Route path="/time" element={<TimePage />} />
              <Route path="/data-quality" element={<DataQualityPage />} />
              <Route path="/indicators" element={<IndicatorsPage />} />
              <Route path="/ontology" element={<OntologyPage />} />
              <Route path="/site-selection" element={<SiteSelectionPage />} />
              <Route path="/smart-scheduling" element={<SmartSchedulingPage />} />
              <Route path="/situational-awareness" element={<SituationalAwarenessPage />} />
              <Route path="/login" element={<Navigate to="/" />} />
              <Route path="*" element={<Navigate to="/" />} />
            </Routes>
          </Layout>
        )}
      </BrowserRouter>
    </QueryClientProvider>
  )
}
