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 { StorePage } from '@/pages/StorePage'
import { StoreDetailPage } from '@/pages/StoreDetailPage'
import { MonthlyReviewPage } from '@/pages/MonthlyReviewPage'
import { IndicatorsPage } from '@/pages/IndicatorsPage'
import { RegionalPage } from '@/pages/RegionalPage'
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 { CentralKitchenPage } from '@/pages/CentralKitchenPage'
import { DistributionReconciliationPage } from '@/pages/DistributionReconciliationPage'
import { BomPenetrationPage } from '@/pages/BomPenetrationPage'
import { ProductionPlanPage } from '@/pages/ProductionPlanPage'
import { LoginPage } from '@/pages/LoginPage'
import { MemberLTVPage } from '@/pages/MemberLTVPage'
import { MenuEngineeringPage } from '@/pages/MenuEngineeringPage'
import { RegionComparisonPage } from '@/pages/RegionComparisonPage'
import { EmployeePerformancePage } from '@/pages/EmployeePerformancePage'
import { InventoryTurnoverPage } from '@/pages/InventoryTurnoverPage'
import { TenantManagementPage } from './pages/TenantManagementPage'
import { TenantUsersPage } from './pages/TenantUsersPage'
import { RoleRoute } from './components/RoleRoute'

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={user?.role === 'platform_admin' ? <Navigate to="/tenant-management" /> : user?.role === 'store' ? <Navigate to="/store" /> : user?.role === 'regional' ? <Navigate to="/regional" /> : <DashboardPage />} />
              <Route path="/boss" element={<RoleRoute roles={['hq','dept']}><BossPage /></RoleRoute>} />
              <Route path="/revenue" element={<RoleRoute roles={['hq','dept']}><RevenuePage /></RoleRoute>} />
              <Route path="/bank" element={<RoleRoute roles={['hq']}><BankPage /></RoleRoute>} />
              <Route path="/central-kitchen" element={<RoleRoute roles={['hq','dept']}><CentralKitchenPage /></RoleRoute>} />
              <Route path="/distribution-reconciliation" element={<RoleRoute roles={['hq','dept']}><DistributionReconciliationPage /></RoleRoute>} />
              <Route path="/bom-penetration" element={<RoleRoute roles={['hq','dept']}><BomPenetrationPage /></RoleRoute>} />
              <Route path="/production-plan" element={<RoleRoute roles={['hq','dept']}><ProductionPlanPage /></RoleRoute>} />
              <Route path="/regional" element={<RoleRoute roles={['hq','dept','regional']}><RegionalPage /></RoleRoute>} />
              <Route path="/store" element={<RoleRoute roles={['hq','dept','store']}><StorePage /></RoleRoute>} />
              <Route path="/tasks" element={<RoleRoute roles={['hq','regional','store','dept']}><TasksPage /></RoleRoute>} />
              <Route path="/tasks/:id" element={<RoleRoute roles={['hq','regional','store','dept']}><TaskDetailPage /></RoleRoute>} />
              <Route path="/stores/:code" element={<RoleRoute roles={['hq','regional','store','dept']}><StoreDetailPage /></RoleRoute>} />
              <Route path="/monthly-review" element={<RoleRoute roles={['hq','dept','regional']}><MonthlyReviewPage /></RoleRoute>} />
              <Route path="/sku" element={<RoleRoute roles={['hq','dept']}><SKUPage /></RoleRoute>} />
              <Route path="/cost" element={<RoleRoute roles={['hq','dept']}><CostPage /></RoleRoute>} />
              <Route path="/cost-analysis" element={<RoleRoute roles={['hq','dept']}><CostAnalysisPage /></RoleRoute>} />
              <Route path="/store-expense" element={<RoleRoute roles={['hq','dept']}><StoreExpensePage /></RoleRoute>} />
              <Route path="/platform" element={<RoleRoute roles={['hq','dept']}><PlatformPage /></RoleRoute>} />
              <Route path="/member" element={<RoleRoute roles={['hq','dept']}><MemberPage /></RoleRoute>} />
              <Route path="/risk" element={<RoleRoute roles={['hq','dept']}><RiskPage /></RoleRoute>} />
              <Route path="/time" element={<RoleRoute roles={['hq','dept']}><TimePage /></RoleRoute>} />
              <Route path="/data-quality" element={<RoleRoute roles={['hq','dept']}><DataQualityPage /></RoleRoute>} />
              <Route path="/indicators" element={<RoleRoute roles={['hq','dept','regional','store']}><IndicatorsPage /></RoleRoute>} />
              <Route path="/ontology" element={<RoleRoute roles={['hq','dept']}><OntologyPage /></RoleRoute>} />
              <Route path="/site-selection" element={<RoleRoute roles={['hq','dept']}><SiteSelectionPage /></RoleRoute>} />
              <Route path="/smart-scheduling" element={<RoleRoute roles={['hq','dept','regional','store']}><SmartSchedulingPage /></RoleRoute>} />
              <Route path="/situational-awareness" element={<RoleRoute roles={['hq','dept','regional','store']}><SituationalAwarenessPage /></RoleRoute>} />
              <Route path="/login" element={<Navigate to="/" />} />
              <Route path="/member-ltv" element={<RoleRoute roles={['hq','dept']}><MemberLTVPage /></RoleRoute>} />
              <Route path="/menu-engineering" element={<RoleRoute roles={['hq','dept']}><MenuEngineeringPage /></RoleRoute>} />
              <Route path="/region-comparison" element={<RoleRoute roles={['hq','dept','regional']}><RegionComparisonPage /></RoleRoute>} />
              <Route path="/employee-performance" element={<RoleRoute roles={['hq','dept']}><EmployeePerformancePage /></RoleRoute>} />
              <Route path="/inventory-turnover" element={<RoleRoute roles={['hq','dept']}><InventoryTurnoverPage /></RoleRoute>} />
              <Route path="/tenant-management" element={<RoleRoute roles={['platform_admin']}><TenantManagementPage /></RoleRoute>} />
              <Route path="/tenant-users" element={<RoleRoute roles={['hq']}><TenantUsersPage /></RoleRoute>} />
              <Route path="*" element={<Navigate to="/" />} />
            </Routes>
          </Layout>
        )}
      </BrowserRouter>
    </QueryClientProvider>
  )
}
