import React from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

import { Layout } from '@/components/layout/Layout';
import { Dashboard } from '@/pages/Dashboard';
import { TenantList } from '@/pages/Tenants/TenantList';
import { UserList } from '@/pages/Users/UserList';
import { RoleEditor } from '@/pages/Roles/RoleEditor';
import { BillingPage } from '@/pages/Billing/BillingPage';
import { AuditLogPage } from '@/pages/AuditLogs/AuditLogPage';
import { ReportBuilder } from '@/pages/Reports/ReportBuilder';
import { PluginManager } from '@/pages/Plugins/PluginManager';
import { useAuth } from '@/hooks/useAuth';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // 5 minutes
      retry: 1,
    },
  },
});

function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const { isAuthenticated } = useAuth();
  return isAuthenticated ? <>{children}</> : <Navigate to="/login" />;
}

function AppRoutes() {
  return (
    <Routes>
      <Route path="/login" element={<div>Login Page</div>} />
      <Route
        path="/*"
        element={
          <ProtectedRoute>
            <Layout>
              <Routes>
                <Route path="/" element={<Dashboard />} />
                <Route path="/tenants" element={<TenantList />} />
                <Route path="/tenants/:id" element={<div>Tenant Detail</div>} />
                <Route path="/users" element={<UserList />} />
                <Route path="/users/:id" element={<div>User Detail</div>} />
                <Route path="/roles" element={<div>Roles List</div>} />
                <Route path="/roles/:id" element={<RoleEditor />} />
                <Route path="/api-keys" element={<div>API Keys</div>} />
                <Route path="/billing" element={<BillingPage />} />
                <Route path="/audit-logs" element={<AuditLogPage />} />
                <Route path="/reports" element={<ReportBuilder />} />
                <Route path="/reports/new" element={<div>New Report</div>} />
                <Route path="/plugins" element={<PluginManager />} />
                <Route path="/settings" element={<div>Settings</div>} />
              </Routes>
            </Layout>
          </ProtectedRoute>
        }
      />
    </Routes>
  );
}

export function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <BrowserRouter>
        <AppRoutes />
      </BrowserRouter>
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  );
}
