import React, { Suspense } from 'react';
import { HashRouter, Routes, Route, Navigate, useParams } from 'react-router-dom';
import { ThemeProvider } from './contexts/ThemeContext';
import { AuthProvider, useAuth } from './contexts/AuthContext';
import { UserOrganizationsProvider, useUserOrganizations } from './contexts/UserOrganizationsContext';
import { OrgProvider, useOrg } from './contexts/OrgContext';

// Lazy load all page components for better performance
const Layout = React.lazy(() => import('./components/UiKit').then(module => ({ default: module.Layout })));
const CompanyWiki = React.lazy(() => import('./pages/CompanyWiki'));
const Reports = React.lazy(() => import('./pages/Reports'));
const Submissions = React.lazy(() => import('./pages/Submissions'));
const Chat = React.lazy(() => import('./pages/Chat'));
const HelpNew = React.lazy(() => import('./pages/Help'));
const SettingsNew = React.lazy(() => import('./pages/Settings'));
const ModernLogin = React.lazy(() => import('./pages/Login'));
const OrgSelection = React.lazy(() => import('./pages/OrgSelection'));
const Onboarding = React.lazy(() => import('./pages/Onboarding'));
const EmployeeQuestionnaireNew = React.lazy(() => import('./pages/EmployeeQuestionnaire'));
const QuestionTypesDemo = React.lazy(() => import('./pages/QuestionTypesDemo'));
const FormsDashboard = React.lazy(() => import('./pages/FormsDashboard'));
const SubscriptionSetup = React.lazy(() => import('./pages/SubscriptionSetup'));

// Loading component for Suspense fallback
const LoadingSpinner: React.FC = () => (
  <div className="min-h-screen flex items-center justify-center">
    <div className="animate-spin rounded-full h-8 w-8 border-2 border-gray-900 border-t-transparent"></div>
  </div>
);

// Suspense wrapper for lazy components
const SuspenseWrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => (
  <Suspense fallback={<LoadingSpinner />}>
    {children}
  </Suspense>
);

const RequireAuth: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { user, loading } = useAuth();

  if (loading) return <div className="p-8">Loading...</div>;
  if (!user) return <Navigate to="/login" replace />;
  return <>{children}</>;
};

const RequireOrgSelection: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { selectedOrgId, loading } = useUserOrganizations();

  if (loading) return <div className="p-8">Loading your organizations...</div>;
  if (!selectedOrgId) return <Navigate to="/org-selection" replace />;
  return <>{children}</>;
};

const RequireOnboarding: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { org } = useOrg();
  const { user } = useAuth();
  const { organizations, selectedOrgId } = useUserOrganizations();

  if (!org) return <div className="p-8">Loading organization...</div>;

  const userOrgRelation = organizations.find(o => o.orgId === selectedOrgId);
  const isOrgOwner = userOrgRelation?.role === 'owner';
  const onboardingCompleted = org.onboardingCompleted === true;

  console.log('RequireOnboarding check:', {
    orgId: selectedOrgId,
    orgOnboardingCompleted: org.onboardingCompleted,
    userRole: userOrgRelation?.role,
    finalDecision: onboardingCompleted
  });

  if (!onboardingCompleted) {
    if (isOrgOwner) {
      console.log('Redirecting owner to onboarding');
      return <Navigate to="/onboarding" replace />;
    } else {
      // Non-owners should see a waiting message
      return (
        <div className="p-8 text-center">
          <h2 className="text-xl font-semibold mb-4">Organization Setup In Progress</h2>
          <p className="text-gray-600">
            Your organization is currently being set up by the administrator.
            Please check back later or contact your administrator for more information.
          </p>
        </div>
      );
    }
  }

  return <>{children}</>;
};

// Wrapper component that provides selected org to OrgProvider
const OrgProviderWrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { selectedOrgId } = useUserOrganizations();

  if (!selectedOrgId) {
    return <div className="p-8">No organization selected</div>;
  }

  return (
    <OrgProvider selectedOrgId={selectedOrgId}>
      {children}
    </OrgProvider>
  );
};

// Redirect invite URLs directly to employee questionnaire (no auth needed)
const InviteRedirect: React.FC = () => {
  const { inviteCode } = useParams<{ inviteCode: string }>();
  return <Navigate to={`/employee-form/${inviteCode}`} replace />;
};

function App() {
  return (
    <ThemeProvider>
      <AuthProvider>
        <UserOrganizationsProvider>
          <HashRouter>
            <Routes>
              <Route path="/login" element={<SuspenseWrapper><ModernLogin /></SuspenseWrapper>} />
              <Route path="/login/:inviteCode" element={<SuspenseWrapper><ModernLogin /></SuspenseWrapper>} />

              {/* Employee questionnaire - no auth needed, uses invite code */}
              <Route path="/employee-form/:inviteCode" element={<SuspenseWrapper><EmployeeQuestionnaireNew /></SuspenseWrapper>} />
              <Route path="/questionnaire/:inviteCode" element={<SuspenseWrapper><EmployeeQuestionnaireNew /></SuspenseWrapper>} />

              {/* Organization Selection - after auth, before entering app */}
              <Route
                path="/org-selection"
                element={
                  <RequireAuth>
                    <SuspenseWrapper><OrgSelection /></SuspenseWrapper>
                  </RequireAuth>
                }
              />

              {/* Subscription Setup - after organization creation */}
              <Route
                path="/subscription-setup"
                element={
                  <RequireAuth>
                    <SuspenseWrapper><SubscriptionSetup /></SuspenseWrapper>
                  </RequireAuth>
                }
              />

              {/* Routes that require both auth and org selection */}
              <Route
                path="/employee-questionnaire"
                element={
                  <RequireAuth>
                    <RequireOrgSelection>
                      <OrgProviderWrapper>
                        <SuspenseWrapper><EmployeeQuestionnaireNew /></SuspenseWrapper>
                      </OrgProviderWrapper>
                    </RequireOrgSelection>
                  </RequireAuth>
                }
              />

              <Route
                path="/onboarding"
                element={
                  <RequireAuth>
                    <RequireOrgSelection>
                      <OrgProviderWrapper>
                        <SuspenseWrapper><Onboarding /></SuspenseWrapper>
                      </OrgProviderWrapper>
                    </RequireOrgSelection>
                  </RequireAuth>
                }
              />

              {/* New Figma Chat Implementation - Standalone route */}
              <Route
                path="/chat"
                element={
                  <RequireAuth>
                    <RequireOrgSelection>
                      <OrgProviderWrapper>
                        <RequireOnboarding>
                          <SuspenseWrapper><Chat /></SuspenseWrapper>
                        </RequireOnboarding>
                      </OrgProviderWrapper>
                    </RequireOrgSelection>
                  </RequireAuth>
                }
              />
              {/* New Figma Help Implementation - Standalone route */}
              <Route
                path="/help"
                element={
                  <RequireAuth>
                    <RequireOrgSelection>
                      <OrgProviderWrapper>
                        <RequireOnboarding>
                          <SuspenseWrapper><HelpNew /></SuspenseWrapper>
                        </RequireOnboarding>
                      </OrgProviderWrapper>
                    </RequireOrgSelection>
                  </RequireAuth>
                }
              />

              {/* New Figma Settings Implementation - Standalone route */}
              <Route
                path="/settings"
                element={
                  <RequireAuth>
                    <RequireOrgSelection>
                      <OrgProviderWrapper>
                        <RequireOnboarding>
                          <SuspenseWrapper><SettingsNew /></SuspenseWrapper>
                        </RequireOnboarding>
                      </OrgProviderWrapper>
                    </RequireOrgSelection>
                  </RequireAuth>
                }
              />

              {/* Main app routes - require auth, org selection, and completed onboarding */}
              <Route
                element={
                  <RequireAuth>
                    <RequireOrgSelection>
                      <OrgProviderWrapper>
                        <RequireOnboarding>
                          <SuspenseWrapper><Layout /></SuspenseWrapper>
                        </RequireOnboarding>
                      </OrgProviderWrapper>
                    </RequireOrgSelection>
                  </RequireAuth>
                }
              >
                <Route path="/" element={<Navigate to="/reports" replace />} />
                <Route path="/company-wiki" element={<SuspenseWrapper><CompanyWiki /></SuspenseWrapper>} />
                <Route path="/submissions" element={<SuspenseWrapper><Submissions /></SuspenseWrapper>} />
                <Route path="/reports" element={<SuspenseWrapper><Reports /></SuspenseWrapper>} />
              </Route>

              {/* Debug routes */}
              <Route
                path="/question-types-demo"
                element={
                  <RequireAuth>
                    <RequireOrgSelection>
                      <OrgProviderWrapper>
                        <SuspenseWrapper><QuestionTypesDemo /></SuspenseWrapper>
                      </OrgProviderWrapper>
                    </RequireOrgSelection>
                  </RequireAuth>
                }
              />
              <Route
                path="/forms-dashboard"
                element={
                  <RequireAuth>
                    <RequireOrgSelection>
                      <OrgProviderWrapper>
                        <SuspenseWrapper><FormsDashboard /></SuspenseWrapper>
                      </OrgProviderWrapper>
                    </RequireOrgSelection>
                  </RequireAuth>
                }
              />
            </Routes>
          </HashRouter>
        </UserOrganizationsProvider>
      </AuthProvider>
    </ThemeProvider>
  );
}

export default App;